Skip to content

Commit

Permalink
Merge pull request #30 from NJUPT-SAST/dev-xun
Browse files Browse the repository at this point in the history
modify authorize api request method to get
  • Loading branch information
Xunop authored Sep 5, 2023
2 parents ff12f36 + 4f1d7af commit c4a7452
Show file tree
Hide file tree
Showing 9 changed files with 142 additions and 20 deletions.
12 changes: 4 additions & 8 deletions api/v1/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,21 +134,18 @@ func OauthUserInfo(c *gin.Context) {
}))
}

// redirect user to login for authorization
func Authorize(c *gin.Context) {
r := c.Request
w := c.Writer
_ = r.ParseMultipartForm(0)
_ = r.ParseForm()
store, err := session.Start(c, w, r)
if err != nil {
c.JSON(http.StatusInternalServerError, result.Failed(result.InternalErr.Wrap(err)))
return
}
_ = r.ParseForm()
var form url.Values
if v, ok := store.Get("ReturnUri"); ok {
form = v.(url.Values)
form.Add("token", r.Form.Get("token"))
}
r.Form = form

Expand Down Expand Up @@ -245,12 +242,11 @@ func userAuthorizeHandler(w http.ResponseWriter, r *http.Request) (userID string
return
}

// check if user is logged in
_ = r.ParseMultipartForm(0)
_ = r.ParseForm()
token := r.Form.Get("token")
token := r.Form.Get("part")
if token == "" {
if r.Form == nil {
// check if user is logged in
_ = r.ParseMultipartForm(0)
_ = r.ParseForm()
}

Expand Down
15 changes: 10 additions & 5 deletions api/v1/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package v1

import (
"net/http"
"strings"

"github.com/NJUPT-SAST/sast-link-backend/model"

Expand All @@ -27,7 +28,7 @@ func Register(ctx *gin.Context) {
return
}

ticket := ctx.GetHeader("REGISTER_TICKET")
ticket := ctx.GetHeader("REGISTER-TICKET")
username, usernameErr := util.GetUsername(ticket)
if usernameErr != nil {
ctx.JSON(http.StatusBadRequest, result.Failed(result.HandleError(usernameErr)))
Expand All @@ -44,7 +45,7 @@ func Register(ctx *gin.Context) {

func CheckVerifyCode(ctx *gin.Context) {
code, codeFlag := ctx.GetPostForm("captcha")
ticket := ctx.GetHeader("REGISTER_TICKET")
ticket := ctx.GetHeader("REGISTER-TICKET")
if !codeFlag {
ctx.JSON(http.StatusBadRequest, result.Failed(result.ParamError))
return
Expand All @@ -70,12 +71,13 @@ func UserInfo(ctx *gin.Context) {
}

ctx.JSON(http.StatusOK, result.Success(gin.H{
"email": user.Email,
"email": user.Email,
"user_id": user.Uid,
}))
}

func SendEmail(ctx *gin.Context) {
ticket := ctx.GetHeader("REGISTER_TICKET")
ticket := ctx.GetHeader("REGISTER-TICKET")
username, usernameErr := util.GetUsername(ticket)
// 错误处理机制写玉玉了
// 我开始乱写了啊啊啊啊
Expand Down Expand Up @@ -103,6 +105,9 @@ func SendEmail(ctx *gin.Context) {

func VerifyAccount(ctx *gin.Context) {
username := ctx.Query("username")
// Capitalize the username
username = strings.ToLower(username)

flag := ctx.Query("flag")
tKey := ""
// 0 is register
Expand Down Expand Up @@ -131,7 +136,7 @@ func VerifyAccount(ctx *gin.Context) {
}

func Login(ctx *gin.Context) {
ticket := ctx.GetHeader("LOGIN_TICKET")
ticket := ctx.GetHeader("LOGIN-TICKET")
password := ctx.PostForm("password")
if ticket == "" {
ctx.JSON(http.StatusBadRequest, result.Failed(result.CHECK_TICKET_NOTFOUND))
Expand Down
16 changes: 16 additions & 0 deletions example/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,22 @@ func main() {
http.Redirect(w, r, u, http.StatusFound)
})

http.HandleFunc("/api/auth/callback/sastlink", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
println(r.URL.RawQuery)
state := r.Form.Get("state")
if state != "xyz" {
http.Error(w, "State invalid", http.StatusBadRequest)
return
}
code := r.Form.Get("code")
if code == "" {
http.Error(w, "Code not found", http.StatusBadRequest)
return
}
fmt.Println("Code:" + code)
})

http.HandleFunc("/oauth2", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
println(r.URL.RawQuery)
Expand Down
2 changes: 1 addition & 1 deletion example/static/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ <h1>Login In</h1>

if (token) {
const headers = new Headers();
headers.append("LOGIN_TICKET", token);
headers.append("LOGIN-TICKET", token);
var formdata = new FormData();
formdata.append("password", password);

Expand Down
96 changes: 96 additions & 0 deletions middleware/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package middleware

import (
"net/http"
"net/url"
"strings"
"time"

"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)

func MiddlewareLogging(log *logrus.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
// Start timer
start := time.Now()

// Process request
c.Next()

// Stop timer
end := time.Now()
latency := end.Sub(start)

// Get request status code
status := c.Writer.Status()

baseFields := logrus.Fields{
"status": status,
"method": c.Request.Method,
"path": c.Request.URL.Path,
"ip": c.ClientIP(),
"latency": latency,
}

switch log.GetLevel() {
case logrus.DebugLevel:
// Get params
var params = url.Values{}
if c.Request.Method == "GET" {
params = c.Request.URL.Query()
} else if c.Request.Method == "POST" {
err := c.Request.ParseForm()
if err != nil {
log.WithFields(baseFields).Error("Error parsing form")
}
err = c.Request.ParseMultipartForm(0)
if err != nil {
log.WithFields(baseFields).Error("Error parsing form")
}
params = c.Request.PostForm
} else {
params = c.Request.URL.Query()
}

formatParams := formatParams(params)
// Format headers for readability
formattedHeaders := formatHeaders(c.Request.Header)

// Create a formatted log entry
logEntry := log.WithFields(baseFields)
logEntry = logEntry.WithField("params", formatParams)
logEntry = logEntry.WithField("headers", formattedHeaders)
logEntry.Debug("Request details")
case logrus.InfoLevel:
logEntry := log.WithFields(baseFields)
logEntry.Info("Request details")
}
}
}

func formatHeaders(headers http.Header) string {
var formattedHeaders strings.Builder

for key, values := range headers {
formattedHeaders.WriteString(key)
formattedHeaders.WriteString(": [")
formattedHeaders.WriteString(strings.Join(values, ", "))
formattedHeaders.WriteString("] ")
}

return formattedHeaders.String()
}

func formatParams(params url.Values) string {
var formattedParams strings.Builder

for key, values := range params {
formattedParams.WriteString(key)
formattedParams.WriteString(": [")
formattedParams.WriteString(strings.Join(values, ", "))
formattedParams.WriteString("] ")
}

return formattedParams.String()
}
5 changes: 3 additions & 2 deletions model/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func CheckPassword(username string, password string) (bool, error) {
// return true if user exist
func CheckUserByEmail(email string) (bool, error) {
var user User
err := Db.Where("email = ?", email).First(&user).Error
err := Db.Where("email = ?", email).Where("is_deleted = ?", false).First(&user).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
userLogger.Infof("User [%s] Not Exist\n", email)
Expand Down Expand Up @@ -94,9 +94,10 @@ func CheckUserByUid(uid string) (bool, error) {

func UserInfo(username string) (*User, error) {
var user = User{Uid: &username}
if err := Db.First(&user).Error; err != nil {
if err := Db.Where("email = ?", username).First(&user).Error; err != nil {
return nil, fmt.Errorf("%v: User [%s] Not Exist\n", err, username)
}

return &user, nil
}

Expand Down
6 changes: 5 additions & 1 deletion router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ import (
"net/http"

v1 "github.com/NJUPT-SAST/sast-link-backend/api/v1"
"github.com/NJUPT-SAST/sast-link-backend/log"
"github.com/NJUPT-SAST/sast-link-backend/middleware"
"github.com/gin-gonic/gin"
)

func InitRouter() *gin.Engine {
r := gin.New()
var midLog = log.Log
r.Use(middleware.MiddlewareLogging(midLog))
// FIXME: need discuss on web log
// r.Use(middleware.WebLogger)
r.GET("/ping", func(c *gin.Context) {
Expand Down Expand Up @@ -39,7 +43,7 @@ func InitRouter() *gin.Engine {
oauth := apiV1.Group("/oauth2")
{
// authorize
oauth.Any("/authorize", v1.Authorize)
oauth.GET("/authorize", v1.Authorize)
// login
oauth.GET("/auth", v1.UserAuth)
oauth.POST("/token", v1.AccessToken)
Expand Down
2 changes: 2 additions & 0 deletions service/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package service

import (
"regexp"
"strings"

"github.com/NJUPT-SAST/sast-link-backend/log"
"github.com/NJUPT-SAST/sast-link-backend/model"
Expand All @@ -16,6 +17,7 @@ var serviceLogger = log.Log
func CreateUser(email string, password string) error {
split := regexp.MustCompile(`@`)
uid := split.Split(email, 2)[0]
uid = strings.ToLower(uid)
err := model.CreateUser(&model.User{
Email: &email,
Password: &password,
Expand Down
8 changes: 5 additions & 3 deletions util/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,18 +80,20 @@ func GetUsername(token string) (string, error) {
if err != nil {
return "", err
}

validError := claims.Valid()
if validError != nil {
return "", validError
}

username, claimsError := claims.GetAudience()
if claimsError != nil {
return "", claimsError
}
// redis ticket is username-register
return strings.Split(username[0], "-")[0], nil
uid, err := strings.Split(username[0], "-")[0], nil

return strings.ToLower(uid), err
}

// JWTAccessClaims jwt claims
Expand Down

0 comments on commit c4a7452

Please sign in to comment.