51 lines
983 B
Go
51 lines
983 B
Go
package routes
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"stereo.cat/backend/internal/auth"
|
|
"stereo.cat/backend/internal/types"
|
|
)
|
|
|
|
func RegisterAuthRoutes(cfg *types.StereoConfig, api *gin.RouterGroup) {
|
|
api.GET("/auth/callback", func(c *gin.Context) {
|
|
code := c.Query("code")
|
|
|
|
t, err := cfg.Client.ExchangeCode(code)
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
user, err := cfg.Client.GetUser(t)
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
jwt, err := auth.GenerateJWT(cfg.JWTSecret, user, uint64(time.Now().Add(time.Second*time.Duration(t.ExpiresIn)).Unix()))
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
res := cfg.Database.FirstOrCreate(&user)
|
|
|
|
if res.Error != nil {
|
|
panic(res.Error)
|
|
}
|
|
|
|
// TODO: redirect to dashboard
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"jwt": jwt,
|
|
"known": res.RowsAffected == 0,
|
|
})
|
|
})
|
|
|
|
api.GET("/auth/me", auth.JwtMiddleware(cfg.JWTSecret), func(c *gin.Context) {
|
|
claims, _ := c.Get("claims")
|
|
c.JSON(http.StatusOK, claims)
|
|
})
|
|
}
|