Refactor session loading and allow OAuth 2.0 requests
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
atsebaytClient = config.Client( oauth2.NoContext, &oauth2.Token{ AccessToken: atsebaytToken, }, )
This commit is contained in:
parent
b688a98802
commit
3a3acafa8e
54
api.go
54
api.go
@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@ -76,28 +77,43 @@ func adminRestricted(u *User, c *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func getSessionFromRequest(c *gin.Context) (*Session, error) {
|
||||
var encodedSession string
|
||||
|
||||
if cookie, err := c.Request.Cookie("auth"); err == nil {
|
||||
encodedSession = cookie.Value
|
||||
} else if flds := strings.Fields(c.GetHeader("Authorization")); len(flds) == 2 && flds[0] == "Bearer" {
|
||||
encodedSession = flds[1]
|
||||
}
|
||||
|
||||
if len(encodedSession) > 0 {
|
||||
if sessionid, err := base64.StdEncoding.DecodeString(encodedSession); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return getSession(sessionid)
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func authMiddleware(access ...func(*User, *gin.Context) bool) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
session, err := getSessionFromRequest(c)
|
||||
if err != nil {
|
||||
eraseCookie(c)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"errmsg": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var user *User = nil
|
||||
var session *Session = nil
|
||||
if cookie, err := c.Request.Cookie("auth"); err == nil {
|
||||
if sessionid, err := base64.StdEncoding.DecodeString(cookie.Value); err != nil {
|
||||
eraseCookie(c)
|
||||
c.AbortWithStatusJSON(http.StatusNotAcceptable, gin.H{"errmsg": err.Error()})
|
||||
return
|
||||
} else if session, err = getSession(sessionid); err != nil {
|
||||
eraseCookie(c)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"errmsg": err.Error()})
|
||||
return
|
||||
} else if session.IdUser == nil {
|
||||
user = nil
|
||||
} else if std, err := getUser(int(*session.IdUser)); err != nil {
|
||||
eraseCookie(c)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"errmsg": err.Error()})
|
||||
return
|
||||
} else {
|
||||
user = std
|
||||
}
|
||||
if session == nil || session.IdUser == nil {
|
||||
user = nil
|
||||
} else if std, err := getUser(int(*session.IdUser)); err != nil {
|
||||
eraseCookie(c)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"errmsg": err.Error()})
|
||||
return
|
||||
} else {
|
||||
user = std
|
||||
}
|
||||
|
||||
// Check access limitation
|
||||
|
Reference in New Issue
Block a user