fasten-onprem/backend/pkg/web/handler/auth.go

69 lines
2.6 KiB
Go

package handler
import (
"fmt"
"github.com/fastenhealth/fasten-onprem/backend/pkg"
"github.com/fastenhealth/fasten-onprem/backend/pkg/auth"
"github.com/fastenhealth/fasten-onprem/backend/pkg/config"
"github.com/fastenhealth/fasten-onprem/backend/pkg/database"
"github.com/fastenhealth/fasten-onprem/backend/pkg/models"
"github.com/fastenhealth/fasten-onprem/backend/pkg/utils"
"github.com/gin-gonic/gin"
"net/http"
)
func AuthSignup(c *gin.Context) {
databaseRepo := c.MustGet(pkg.ContextKeyTypeDatabase).(database.DatabaseRepository)
appConfig := c.MustGet(pkg.ContextKeyTypeConfig).(config.Interface)
var userWizard models.UserWizard
if err := c.ShouldBindJSON(&userWizard); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
return
}
err := databaseRepo.CreateUser(c, userWizard.User)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
return
}
//TODO: we can derive the encryption key and the hash'ed user from the responseData sub. For now the Sub will be the user id prepended with hello.
userFastenToken, err := auth.JwtGenerateFastenTokenFromUser(*userWizard.User, appConfig.GetString("jwt.issuer.key"))
//check if the user wants to join the mailing list
if userWizard.JoinMailingList {
//ignore error messages, we don't want to block the user from signing up
utils.JoinNewsletter(userWizard.FullName, userWizard.Email, "", "")
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": userFastenToken})
}
func AuthSignin(c *gin.Context) {
databaseRepo := c.MustGet(pkg.ContextKeyTypeDatabase).(database.DatabaseRepository)
appConfig := c.MustGet(pkg.ContextKeyTypeConfig).(config.Interface)
var user models.User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
return
}
foundUser, err := databaseRepo.GetUserByUsername(c, user.Username)
if err != nil || foundUser == nil {
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": fmt.Sprintf("could not find user: %s", user.Username)})
return
}
err = foundUser.CheckPassword(user.Password)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": fmt.Sprintf("username or password does not match: %s", user.Username)})
return
}
//TODO: we can derive the encryption key and the hash'ed user from the responseData sub. For now the Sub will be the user id prepended with hello.
userFastenToken, err := auth.JwtGenerateFastenTokenFromUser(user, appConfig.GetString("jwt.issuer.key"))
c.JSON(http.StatusOK, gin.H{"success": true, "data": userFastenToken})
}