backend/internal/api/routes/auth.go
2025-06-15 12:53:27 +02:00

71 lines
1.9 KiB
Go

/*
Copyright (C) 2025 hexlocation (hex@iwakura.rip) & grngxd (grng@iwakura.rip)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package routes
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"stereo.cat/backend/internal/auth/token"
"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 := token.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,
})
*/
c.SetCookie("jwt", jwt, int(t.ExpiresIn), "", cfg.Domain, true, true)
c.Redirect(http.StatusTemporaryRedirect, cfg.FrontendUri+"?jwt_set=true")
})
api.GET("/auth/me", token.JwtMiddleware(cfg.JWTSecret), func(c *gin.Context) {
claims, _ := c.Get("claims")
c.JSON(http.StatusOK, claims)
})
}