Files
2021-02-26 23:14:34 +11:00

188 lines
5.1 KiB
Go

package handlers
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/getsentry/sentry-go"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/prometheus/common/log"
"github.com/sirupsen/logrus"
"github.com/wahyd4/badger/models"
)
const (
githubHTTPTimeout = 10
)
var (
NoAuthPaths = []string{"/api/badges", "/api/auth", "/api/toggles"}
)
type UsersHandler struct {
DB *gorm.DB
}
type UserAuthenticationRequest struct {
Name string `json:"name" binding:"required"`
GithubID int `json:"githubId" binding:"required"`
GithubUsername string `json:"githubUsername"`
GithubAvatarURL string `json:"githubAvatar" binding:"required"`
Email string `json:"email"`
Token string `json:"token" binding:"required"`
ExpiresAt string `json:"expiresAt"`
}
type UserInfo struct {
ID string `json:"id"`
GithubID string `json:"githubId"`
Token string `json:"token"`
}
func (usersHandler *UsersHandler) AuthRequired(c *gin.Context) {
authorization := c.GetHeader("Authorization")
uid := c.GetHeader("uid")
var user models.User
if len(authorization) != 0 && len(uid) != 0 {
if err := usersHandler.DB.Preload("Token").First(&user, "ulid = ?", uid).Error; err != nil {
logrus.Warn(err)
sentry.CaptureException(err)
c.AbortWithStatusJSON(http.StatusUnauthorized, GeneralError{"invalid credentials"})
return
}
authToken, err := c.Cookie("auth._token.github")
if err != nil {
sentry.CaptureException(fmt.Errorf("no cookie found for user %s", uid))
c.AbortWithStatusJSON(http.StatusUnauthorized, GeneralError{"invalid credentials"})
return
}
//TODO: Currently, I didn't persistent the access token to db and only did front end check
if authorization != authToken {
sentry.CaptureException(fmt.Errorf("token %s not matched with the one in the cookie %s", authorization, authToken))
c.AbortWithStatusJSON(http.StatusUnauthorized, GeneralError{"invalid credentials"})
return
}
// if user.Token.Token != authorization[7:] {
// logrus.Warnf("submitted token %s not match the backend token", authorization)
// sentry.CaptureException(fmt.Errorf("submitted token %s not match the backend token for user %s", authorization, uid))
// c.AbortWithStatusJSON(http.StatusUnauthorized, GeneralError{"invalid credentials"})
// return
// }
}
c.Set("currentUser", user)
requestingAuthRequiredPath := true
for _, noAuthPath := range NoAuthPaths {
if noAuthPath == c.Request.RequestURI {
requestingAuthRequiredPath = false
break
}
}
if requestingAuthRequiredPath && user.ID == 0 {
c.AbortWithStatusJSON(http.StatusUnauthorized, GeneralError{"login required"})
return
}
if user.ID != 0 {
c.Set("loggedIn", true)
c.Set("currentUserID", int(user.ID))
}
}
func (usersHandler *UsersHandler) Authenticate(c *gin.Context) {
var requestBody UserAuthenticationRequest
if err := c.ShouldBindJSON(&requestBody); err != nil {
logrus.Error(err)
sentry.CaptureException(err)
c.JSON(http.StatusBadRequest, GeneralError{"invalid request body"})
return
}
if !validateUser(requestBody.Token) {
c.JSON(http.StatusBadRequest, GeneralError{fmt.Sprintf("invalid token for user %s", requestBody.Name)})
return
}
var user models.User
if err := usersHandler.DB.Preload("Token").First(&user, "name = ?", requestBody.Name).Error; err != nil {
if err == gorm.ErrRecordNotFound {
user = models.User{
Name: requestBody.Name,
ULID: NewULID(),
GithubID: strconv.Itoa(requestBody.GithubID),
GithubUsername: requestBody.GithubUsername,
GithubAvatarURL: requestBody.GithubAvatarURL,
Email: requestBody.Email,
Token: models.Token{
Token: requestBody.Token,
ExpiresAt: requestBody.ExpiresAt,
},
}
} else {
logrus.Error(err)
sentry.CaptureException(err)
c.JSON(http.StatusInternalServerError, GeneralError{"internal error, please try it later"})
return
}
} else {
user.Token.Token = requestBody.Token
user.Token.ExpiresAt = requestBody.ExpiresAt
}
if err := usersHandler.DB.Save(&user).Error; err != nil {
logrus.Error(err)
sentry.CaptureException(err)
c.JSON(http.StatusInternalServerError, GeneralError{"internal error, please try it later"})
return
}
c.JSON(http.StatusOK, UserInfo{
ID: user.ULID,
GithubID: user.GithubID,
Token: user.Token.Token,
})
}
func validateUser(token string) bool {
client := &http.Client{
Timeout: time.Second * githubHTTPTimeout,
}
req, err := http.NewRequest("GET", "https://api.github.com/user", nil)
if err != nil {
logrus.Error(err)
sentry.CaptureException(err)
return false
}
req.Header.Add("Accept", "application/vnd.github.v3+json")
req.Header.Add("Authorization", fmt.Sprintf("token %s", token))
resp, err := client.Do(req)
if err != nil {
logrus.Error(err)
sentry.CaptureException(err)
return false
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logrus.Error(err)
sentry.CaptureException(err)
return false
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
log.Warnf("request with error %s", body)
return false
}
return true
}