package apis import ( "clortho/db" "clortho/users" "github.com/gin-gonic/gin" ) func InitAuthEndpoints(r *gin.RouterGroup) { group := r.Group("/auth") group.POST("/signin", authSignin) group.POST("/signout", authSignout) group.GET("/me", getMe) } type loginRequest struct { Username string `json:"username"` Password string `json:"password"` } func authSignin(c *gin.Context) { var loginRequest loginRequest err := c.BindJSON(&loginRequest) if err != nil { return } user := users.GetUser(loginRequest.Username) if user == nil || user.PasswordHash == nil { c.JSON(200, gin.H{"valid": false}) return } valid := users.CheckPasswordHash(loginRequest.Password, *user.PasswordHash) if !valid { c.JSON(200, gin.H{"valid": false}) return } session := users.NewSession(*user) jwt, err := users.GenerateJwt(session.ID) if err != nil { c.Error(err) c.JSON(500, gin.H{}) return } c.SetCookie("CLORTHO_AUTH", jwt, 3600, "/", "", true, true) c.JSON(200, gin.H{"valid": true}) } func authSignout(c *gin.Context) { c.SetCookie("CLORTHO_AUTH", "", -1, "/", "", true, true) c.JSON(200, gin.H{}) } func getMe(c *gin.Context) { session, hasSession := c.Get("session") if !hasSession { c.JSON(200, gin.H{"loggedIn": false}) } c.JSON(200, gin.H{ "loggedIn": true, "user": session.(*db.UserSession).User, }) }