initial commit

This commit is contained in:
Elias Schneider
2024-08-12 11:00:25 +02:00
commit eaff977b22
241 changed files with 14378 additions and 0 deletions

View File

@@ -0,0 +1,190 @@
package handler
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"golang-rest-api-template/internal/common"
"golang-rest-api-template/internal/common/middleware"
"golang-rest-api-template/internal/model"
"golang-rest-api-template/internal/utils"
"gorm.io/gorm"
"net/http"
"os"
"reflect"
)
func RegisterConfigurationRoutes(group *gin.RouterGroup) {
group.GET("/application-configuration", listApplicationConfigurationHandler)
group.PUT("/application-configuration", updateApplicationConfigurationHandler)
group.GET("/application-configuration/logo", getLogoHandler)
group.GET("/application-configuration/background-image", getBackgroundImageHandler)
group.GET("/application-configuration/favicon", getFaviconHandler)
group.PUT("/application-configuration/logo", middleware.JWTAuth(true), updateLogoHandler)
group.PUT("/application-configuration/favicon", middleware.JWTAuth(true), updateFaviconHandler)
group.PUT("/application-configuration/background-image", middleware.JWTAuth(true), updateBackgroundImageHandler)
}
func listApplicationConfigurationHandler(c *gin.Context) {
// Return also the private configuration variables if the user is admin and showAll is true
showAll := c.GetBool("userIsAdmin") && c.DefaultQuery("showAll", "false") == "true"
var configuration []model.ApplicationConfigurationVariable
var err error
if showAll {
err = common.DB.Find(&configuration).Error
} else {
err = common.DB.Find(&configuration, "is_public = true").Error
}
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(200, configuration)
}
func updateApplicationConfigurationHandler(c *gin.Context) {
var input model.ApplicationConfigurationUpdateDto
if err := c.ShouldBindJSON(&input); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
savedConfigVariables := make([]model.ApplicationConfigurationVariable, 10)
tx := common.DB.Begin()
rt := reflect.ValueOf(input).Type()
rv := reflect.ValueOf(input)
// Loop over the input struct fields and update the related configuration variables
for i := 0; i < rt.NumField(); i++ {
field := rt.Field(i)
key := field.Tag.Get("json")
value := rv.FieldByName(field.Name).String()
// Get the existing configuration variable from the db
var applicationConfigurationVariable model.ApplicationConfigurationVariable
if err := tx.First(&applicationConfigurationVariable, "key = ? AND is_internal = false", key).Error; err != nil {
tx.Rollback()
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.HandlerError(c, http.StatusNotFound, fmt.Sprintf("Invalid configuration variable '%s'", value))
} else {
utils.UnknownHandlerError(c, err)
}
return
}
// Update the value of the existing configuration variable and save it
applicationConfigurationVariable.Value = value
if err := tx.Save(&applicationConfigurationVariable).Error; err != nil {
tx.Rollback()
utils.UnknownHandlerError(c, err)
return
}
savedConfigVariables[i] = applicationConfigurationVariable
}
tx.Commit()
if err := common.LoadDbConfigFromDb(); err != nil {
utils.UnknownHandlerError(c, err)
}
c.JSON(http.StatusOK, savedConfigVariables)
}
func getLogoHandler(c *gin.Context) {
imagType := common.DbConfig.LogoImageType.Value
getImage(c, "logo", imagType)
}
func getFaviconHandler(c *gin.Context) {
getImage(c, "favicon", "ico")
}
func getBackgroundImageHandler(c *gin.Context) {
imageType := common.DbConfig.BackgroundImageType.Value
getImage(c, "background", imageType)
}
func updateLogoHandler(c *gin.Context) {
imageType := common.DbConfig.LogoImageType.Value
updateImage(c, "logo", imageType)
}
func updateFaviconHandler(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
fileType := utils.GetFileExtension(file.Filename)
if fileType != "ico" {
utils.HandlerError(c, http.StatusBadRequest, "File must be of type .ico")
return
}
updateImage(c, "favicon", "ico")
}
func updateBackgroundImageHandler(c *gin.Context) {
imagType := common.DbConfig.BackgroundImageType.Value
updateImage(c, "background", imagType)
}
func getImage(c *gin.Context, name string, imageType string) {
imagePath := fmt.Sprintf("%s/application-images/%s.%s", common.EnvConfig.UploadPath, name, imageType)
mimeType := utils.GetImageMimeType(imageType)
c.Header("Content-Type", mimeType)
c.File(imagePath)
}
func updateImage(c *gin.Context, imageName string, oldImageType string) {
file, err := c.FormFile("file")
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
fileType := utils.GetFileExtension(file.Filename)
if mimeType := utils.GetImageMimeType(fileType); mimeType == "" {
utils.HandlerError(c, http.StatusBadRequest, "File type not supported")
return
}
// Delete the old image if it has a different file type
if fileType != oldImageType {
oldImagePath := fmt.Sprintf("%s/application-images/%s.%s", common.EnvConfig.UploadPath, imageName, oldImageType)
if err := os.Remove(oldImagePath); err != nil {
utils.UnknownHandlerError(c, err)
return
}
}
imagePath := fmt.Sprintf("%s/application-images/%s.%s", common.EnvConfig.UploadPath, imageName, fileType)
err = c.SaveUploadedFile(file, imagePath)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
// Update the file type in the database
key := fmt.Sprintf("%sImageType", imageName)
err = common.DB.Model(&model.ApplicationConfigurationVariable{}).Where("key = ?", key).Update("value", fileType).Error
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
if err := common.LoadDbConfigFromDb(); err != nil {
utils.UnknownHandlerError(c, err)
}
c.Status(http.StatusNoContent)
}

View File

@@ -0,0 +1,415 @@
package handler
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"golang-rest-api-template/internal/common"
"golang-rest-api-template/internal/common/middleware"
"golang-rest-api-template/internal/model"
"golang-rest-api-template/internal/utils"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"net/http"
"os"
"time"
)
func RegisterOIDCRoutes(group *gin.RouterGroup) {
group.POST("/oidc/authorize", middleware.JWTAuth(false), authorizeHandler)
group.POST("/oidc/authorize/new-client", middleware.JWTAuth(false), authorizeNewClientHandler)
group.POST("/oidc/token", createIDTokenHandler)
group.GET("/oidc/clients", middleware.JWTAuth(true), listClientsHandler)
group.POST("/oidc/clients", middleware.JWTAuth(true), createClientHandler)
group.GET("/oidc/clients/:id", getClientHandler)
group.PUT("/oidc/clients/:id", middleware.JWTAuth(true), updateClientHandler)
group.DELETE("/oidc/clients/:id", middleware.JWTAuth(true), deleteClientHandler)
group.POST("/oidc/clients/:id/secret", middleware.JWTAuth(true), createClientSecretHandler)
group.GET("/oidc/clients/:id/logo", getClientLogoHandler)
group.DELETE("/oidc/clients/:id/logo", deleteClientLogoHandler)
group.POST("/oidc/clients/:id/logo", middleware.JWTAuth(true), middleware.LimitFileSize(2<<20), updateClientLogoHandler)
}
type AuthorizeRequest struct {
ClientID string `json:"clientID" binding:"required"`
Scope string `json:"scope" binding:"required"`
Nonce string `json:"nonce"`
}
func authorizeHandler(c *gin.Context) {
var parsedBody AuthorizeRequest
if err := c.ShouldBindJSON(&parsedBody); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
var userAuthorizedOIDCClient model.UserAuthorizedOidcClient
common.DB.First(&userAuthorizedOIDCClient, "client_id = ? AND user_id = ?", parsedBody.ClientID, c.GetString("userID"))
// If the record isn't found or the scope is different return an error
// The client will have to call the authorizeNewClientHandler
if userAuthorizedOIDCClient.Scope != parsedBody.Scope {
utils.HandlerError(c, http.StatusForbidden, "missing authorization")
return
}
authorizationCode, err := createAuthorizationCode(parsedBody.ClientID, c.GetString("userID"), parsedBody.Scope, parsedBody.Nonce)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"code": authorizationCode})
}
// authorizeNewClientHandler authorizes a new client for the user
// a new client is a new client when the user has not authorized the client before
func authorizeNewClientHandler(c *gin.Context) {
var parsedBody model.AuthorizeNewClientDto
if err := c.ShouldBindJSON(&parsedBody); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
userAuthorizedClient := model.UserAuthorizedOidcClient{
UserID: c.GetString("userID"),
ClientID: parsedBody.ClientID,
Scope: parsedBody.Scope,
}
err := common.DB.Create(&userAuthorizedClient).Error
if err != nil && errors.Is(err, gorm.ErrDuplicatedKey) {
err = common.DB.Model(&userAuthorizedClient).Update("scope", parsedBody.Scope).Error
}
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
authorizationCode, err := createAuthorizationCode(parsedBody.ClientID, c.GetString("userID"), parsedBody.Scope, parsedBody.Nonce)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"code": authorizationCode})
}
func createIDTokenHandler(c *gin.Context) {
var body model.OidcIdTokenDto
if err := c.ShouldBind(&body); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
// Currently only authorization_code grant type is supported
if body.GrantType != "authorization_code" {
utils.HandlerError(c, http.StatusBadRequest, "grant type not supported")
return
}
clientID := body.ClientID
clientSecret := body.ClientSecret
// Client id and secret can also be passed over the Authorization header
if clientID == "" || clientSecret == "" {
var ok bool
clientID, clientSecret, ok = c.Request.BasicAuth()
if !ok {
utils.HandlerError(c, http.StatusBadRequest, "Client id and secret not provided")
return
}
}
// Get the client
var client model.OidcClient
err := common.DB.First(&client, "id = ?", clientID, clientSecret).Error
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "OIDC OIDC client not found")
return
}
// Check if client secret is correct
err = bcrypt.CompareHashAndPassword([]byte(client.Secret), []byte(clientSecret))
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid client secret")
return
}
var authorizationCodeMetaData model.OidcAuthorizationCode
err = common.DB.Preload("User").First(&authorizationCodeMetaData, "code = ?", body.Code).Error
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid authorization code")
return
}
// Check if the client id matches the client id in the authorization code and if the code has expired
if authorizationCodeMetaData.ClientID != clientID && authorizationCodeMetaData.ExpiresAt.Before(time.Now()) {
utils.HandlerError(c, http.StatusBadRequest, "invalid authorization code")
return
}
idToken, e := common.GenerateIDToken(authorizationCodeMetaData.User, clientID, authorizationCodeMetaData.Scope, authorizationCodeMetaData.Nonce)
if e != nil {
utils.UnknownHandlerError(c, err)
return
}
// Delete the authorization code after it has been used
common.DB.Delete(&authorizationCodeMetaData)
c.JSON(http.StatusOK, gin.H{"id_token": idToken})
}
func getClientHandler(c *gin.Context) {
clientId := c.Param("id")
var client model.OidcClient
err := common.DB.First(&client, "id = ?", clientId).Error
if err != nil {
utils.HandlerError(c, http.StatusNotFound, "OIDC client not found")
return
}
c.JSON(http.StatusOK, client)
}
func listClientsHandler(c *gin.Context) {
var clients []model.OidcClient
searchTerm := c.Query("search")
query := common.DB.Model(&model.OidcClient{})
if searchTerm != "" {
searchPattern := "%" + searchTerm + "%"
query = query.Where("name LIKE ?", searchPattern)
}
pagination, err := utils.Paginate(c, query, &clients)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"data": clients,
"pagination": pagination,
})
}
func createClientHandler(c *gin.Context) {
var input model.OidcClientCreateDto
if err := c.ShouldBindJSON(&input); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
client := model.OidcClient{
Name: input.Name,
CallbackURL: input.CallbackURL,
CreatedByID: c.GetString("userID"),
}
if err := common.DB.Create(&client).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusCreated, client)
}
func deleteClientHandler(c *gin.Context) {
var client model.OidcClient
if err := common.DB.First(&client, "id = ?", c.Param("id")).Error; err != nil {
utils.HandlerError(c, http.StatusNotFound, "OIDC OIDC client not found")
return
}
if err := common.DB.Delete(&client).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func updateClientHandler(c *gin.Context) {
var input model.OidcClientCreateDto
if err := c.ShouldBindJSON(&input); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
var client model.OidcClient
if err := common.DB.First(&client, "id = ?", c.Param("id")).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.HandlerError(c, http.StatusNotFound, "OIDC client not found")
return
}
utils.UnknownHandlerError(c, err)
return
}
client.Name = input.Name
client.CallbackURL = input.CallbackURL
if err := common.DB.Save(&client).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusNoContent, client)
}
// createClientSecretHandler creates a new secret for the client and revokes the old one
func createClientSecretHandler(c *gin.Context) {
var client model.OidcClient
if err := common.DB.First(&client, "id = ?", c.Param("id")).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.HandlerError(c, http.StatusNotFound, "OIDC client not found")
return
}
utils.UnknownHandlerError(c, err)
return
}
clientSecret, err := utils.GenerateRandomAlphanumericString(32)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
hashedSecret, err := bcrypt.GenerateFromPassword([]byte(clientSecret), bcrypt.DefaultCost)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
client.Secret = string(hashedSecret)
if err := common.DB.Save(&client).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"secret": clientSecret})
}
func getClientLogoHandler(c *gin.Context) {
var client model.OidcClient
if err := common.DB.First(&client, "id = ?", c.Param("id")).Error; err != nil {
utils.HandlerError(c, http.StatusNotFound, "OIDC client not found")
return
}
if client.ImageType == nil {
utils.HandlerError(c, http.StatusNotFound, "image not found")
return
}
imageType := *client.ImageType
imagePath := fmt.Sprintf("%s/oidc-client-images/%s.%s", common.EnvConfig.UploadPath, client.ID, imageType)
mimeType := utils.GetImageMimeType(imageType)
c.Header("Content-Type", mimeType)
c.File(imagePath)
}
func updateClientLogoHandler(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
fileType := utils.GetFileExtension(file.Filename)
if mimeType := utils.GetImageMimeType(fileType); mimeType == "" {
utils.HandlerError(c, http.StatusBadRequest, "file type not supported")
return
}
imagePath := fmt.Sprintf("%s/oidc-client-images/%s.%s", common.EnvConfig.UploadPath, c.Param("id"), fileType)
err = c.SaveUploadedFile(file, imagePath)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
var client model.OidcClient
if err := common.DB.First(&client, "id = ?", c.Param("id")).Error; err != nil {
utils.HandlerError(c, http.StatusNotFound, "OIDC client not found")
return
}
// Delete the old image if it has a different file type
if client.ImageType != nil && fileType != *client.ImageType {
oldImagePath := fmt.Sprintf("%s/oidc-client-images/%s.%s", common.EnvConfig.UploadPath, client.ID, *client.ImageType)
if err := os.Remove(oldImagePath); err != nil {
utils.UnknownHandlerError(c, err)
return
}
}
client.ImageType = &fileType
if err := common.DB.Save(&client).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func deleteClientLogoHandler(c *gin.Context) {
var client model.OidcClient
if err := common.DB.First(&client, "id = ?", c.Param("id")).Error; err != nil {
utils.HandlerError(c, http.StatusNotFound, "OIDC client not found")
return
}
if client.ImageType == nil {
utils.HandlerError(c, http.StatusNotFound, "image not found")
return
}
imagePath := fmt.Sprintf("%s/oidc-client-images/%s.%s", common.EnvConfig.UploadPath, client.ID, *client.ImageType)
if err := os.Remove(imagePath); err != nil {
utils.UnknownHandlerError(c, err)
return
}
client.ImageType = nil
if err := common.DB.Save(&client).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func createAuthorizationCode(clientID string, userID string, scope string, nonce string) (string, error) {
randomString, err := utils.GenerateRandomAlphanumericString(32)
if err != nil {
return "", err
}
oidcAuthorizationCode := model.OidcAuthorizationCode{
ExpiresAt: time.Now().Add(15 * time.Minute),
Code: randomString,
ClientID: clientID,
UserID: userID,
Scope: scope,
Nonce: nonce,
}
if err := common.DB.Create(&oidcAuthorizationCode).Error; err != nil {
return "", err
}
return randomString, nil
}

View File

@@ -0,0 +1,237 @@
package handler
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/base64"
"log"
"os"
"time"
"github.com/fxamacker/cbor/v2"
"github.com/gin-gonic/gin"
"github.com/go-webauthn/webauthn/protocol"
"golang-rest-api-template/internal/common"
"golang-rest-api-template/internal/model"
"golang-rest-api-template/internal/utils"
"gorm.io/gorm"
)
func RegisterTestRoutes(group *gin.RouterGroup) {
group.POST("/test/reset", resetAndSeedHandler)
}
func resetAndSeedHandler(c *gin.Context) {
if err := resetDatabase(); err != nil {
utils.UnknownHandlerError(c, err)
return
}
if err := resetApplicationImages(); err != nil {
utils.UnknownHandlerError(c, err)
return
}
if err := seedDatabase(); err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(200, gin.H{"message": "Database reset and seeded"})
}
// seedDatabase seeds the database with initial data and uses a transaction to ensure atomicity.
func seedDatabase() error {
return common.DB.Transaction(func(tx *gorm.DB) error {
users := []model.User{
{
Base: model.Base{
ID: "f4b89dc2-62fb-46bf-9f5f-c34f4eafe93e",
},
Username: "tim",
Email: "tim.cook@test.com",
FirstName: "Tim",
LastName: "Cook",
IsAdmin: true,
},
{
Base: model.Base{
ID: "1cd19686-f9a6-43f4-a41f-14a0bf5b4036",
},
Username: "craig",
Email: "craig.federighi@test.com",
FirstName: "Craig",
LastName: "Federighi",
IsAdmin: false,
},
}
for _, user := range users {
if err := tx.Create(&user).Error; err != nil {
return err
}
}
oidcClients := []model.OidcClient{
{
Base: model.Base{
ID: "3654a746-35d4-4321-ac61-0bdcff2b4055",
},
Name: "Nextcloud",
Secret: "$2a$10$9dypwot8nGuCjT6wQWWpJOckZfRprhe2EkwpKizxS/fpVHrOLEJHC", // w2mUeZISmEvIDMEDvpY0PnxQIpj1m3zY
CallbackURL: "http://nextcloud/auth/callback",
ImageType: utils.StringPointer("png"),
CreatedByID: users[0].ID,
},
{
Base: model.Base{
ID: "606c7782-f2b1-49e5-8ea9-26eb1b06d018",
},
Name: "Immich",
Secret: "$2a$10$Ak.FP8riD1ssy2AGGbG.gOpnp/rBpymd74j0nxNMtW0GG1Lb4gzxe", // PYjrE9u4v9GVqXKi52eur0eb2Ci4kc0x
CallbackURL: "http://immich/auth/callback",
CreatedByID: users[0].ID,
},
}
for _, client := range oidcClients {
if err := tx.Create(&client).Error; err != nil {
return err
}
}
authCode := model.OidcAuthorizationCode{
Code: "auth-code",
Scope: "openid profile",
Nonce: "nonce",
ExpiresAt: time.Now().Add(1 * time.Hour),
UserID: users[0].ID,
ClientID: oidcClients[0].ID,
}
if err := tx.Create(&authCode).Error; err != nil {
return err
}
accessToken := model.OneTimeAccessToken{
Token: "one-time-token",
ExpiresAt: time.Now().Add(1 * time.Hour),
UserID: users[0].ID,
}
if err := tx.Create(&accessToken).Error; err != nil {
return err
}
userAuthorizedClient := model.UserAuthorizedOidcClient{
Scope: "openid profile email",
UserID: users[0].ID,
ClientID: oidcClients[0].ID,
}
if err := tx.Create(&userAuthorizedClient).Error; err != nil {
return err
}
webauthnCredentials := []model.WebauthnCredential{
{
Name: "Passkey 1",
CredentialID: "test-credential-1",
PublicKey: getCborPublicKey("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEwcOo5KV169KR67QEHrcYkeXE3CCxv2BgwnSq4VYTQxyLtdmKxegexa8JdwFKhKXa2BMI9xaN15BoL6wSCRFJhg=="),
AttestationType: "none",
Transport: model.AuthenticatorTransportList{protocol.Internal},
UserID: users[0].ID,
},
{
Name: "Passkey 2",
CredentialID: "test-credential-2",
PublicKey: getCborPublicKey("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESq/wR8QbBu3dKnpaw/v0mDxFFDwnJ/L5XHSg2tAmq5x1BpSMmIr3+DxCbybVvGRmWGh8kKhy7SMnK91M6rFHTA=="),
AttestationType: "none",
Transport: model.AuthenticatorTransportList{protocol.Internal},
UserID: users[0].ID,
},
}
for _, credential := range webauthnCredentials {
if err := tx.Create(&credential).Error; err != nil {
return err
}
}
webauthnSession := model.WebauthnSession{
Challenge: "challenge",
ExpiresAt: time.Now().Add(1 * time.Hour),
UserVerification: "preferred",
}
if err := tx.Create(&webauthnSession).Error; err != nil {
return err
}
return nil
})
}
// resetDatabase resets the database by deleting all rows from each table.
func resetDatabase() error {
err := common.DB.Transaction(func(tx *gorm.DB) error {
var tables []string
if err := tx.Raw("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name != 'schema_migrations';").Scan(&tables).Error; err != nil {
return err
}
for _, table := range tables {
if err := tx.Exec("DELETE FROM " + table).Error; err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
common.InitDbConfig()
return nil
}
// resetApplicationImages resets the application images by removing existing images and replacing them with the default ones
func resetApplicationImages() error {
if err := os.RemoveAll(common.EnvConfig.UploadPath); err != nil {
log.Printf("Error removing directory: %v", err)
return err
}
if err := utils.CopyDirectory("./images", common.EnvConfig.UploadPath+"/application-images"); err != nil {
log.Printf("Error copying directory: %v", err)
return err
}
return nil
}
// getCborPublicKey decodes a Base64 encoded public key and returns the CBOR encoded COSE key
func getCborPublicKey(base64PublicKey string) []byte {
decodedKey, err := base64.StdEncoding.DecodeString(base64PublicKey)
if err != nil {
log.Fatalf("Failed to decode base64 key: %v", err)
}
pubKey, err := x509.ParsePKIXPublicKey(decodedKey)
if err != nil {
log.Fatalf("Failed to parse public key: %v", err)
}
ecdsaPubKey, ok := pubKey.(*ecdsa.PublicKey)
if !ok {
log.Fatalf("Not an ECDSA public key")
}
coseKey := map[int]interface{}{
1: 2, // Key type: EC2
3: -7, // Algorithm: ECDSA with SHA-256
-1: 1, // Curve: P-256
-2: ecdsaPubKey.X.Bytes(), // X coordinate
-3: ecdsaPubKey.Y.Bytes(), // Y coordinate
}
cborPublicKey, err := cbor.Marshal(coseKey)
if err != nil {
log.Fatalf("Failed to encode CBOR: %v", err)
}
return cborPublicKey
}

View File

@@ -0,0 +1,269 @@
package handler
import (
"errors"
"github.com/gin-gonic/gin"
"golang-rest-api-template/internal/common"
"golang-rest-api-template/internal/common/middleware"
"golang-rest-api-template/internal/model"
"golang-rest-api-template/internal/utils"
"golang.org/x/time/rate"
"gorm.io/gorm"
"log"
"net/http"
"time"
)
func RegisterUserRoutes(group *gin.RouterGroup) {
group.GET("/users", middleware.JWTAuth(true), listUsersHandler)
group.GET("/users/me", middleware.JWTAuth(false), getCurrentUserHandler)
group.GET("/users/:id", middleware.JWTAuth(true), getUserHandler)
group.POST("/users", middleware.JWTAuth(true), createUserHandler)
group.PUT("/users/:id", middleware.JWTAuth(true), updateUserHandler)
group.PUT("/users/me", middleware.JWTAuth(false), updateCurrentUserHandler)
group.DELETE("/users/:id", middleware.JWTAuth(true), deleteUserHandler)
group.POST("/users/:id/one-time-access-token", middleware.JWTAuth(true), createOneTimeAccessTokenHandler)
group.POST("/one-time-access-token/:token", middleware.RateLimiter(rate.Every(10*time.Second), 5), exchangeOneTimeAccessTokenHandler)
group.POST("/one-time-access-token/setup", getSetupAccessTokenHandler)
}
func listUsersHandler(c *gin.Context) {
var users []model.User
searchTerm := c.Query("search")
query := common.DB.Model(&model.User{})
if searchTerm != "" {
searchPattern := "%" + searchTerm + "%"
query = query.Where("email LIKE ? OR first_name LIKE ? OR username LIKE ?", searchPattern, searchPattern, searchPattern)
}
pagination, err := utils.Paginate(c, query, &users)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"data": users,
"pagination": pagination,
})
}
func getUserHandler(c *gin.Context) {
var user model.User
if err := common.DB.Where("id = ?", c.Param("id")).First(&user).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.HandlerError(c, http.StatusNotFound, "User not found")
return
}
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, user)
}
func getCurrentUserHandler(c *gin.Context) {
var user model.User
if err := common.DB.Where("id = ?", c.GetString("userID")).First(&user).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, user)
}
func deleteUserHandler(c *gin.Context) {
var user model.User
if err := common.DB.Where("id = ?", c.Param("id")).First(&user).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.HandlerError(c, http.StatusNotFound, "User not found")
return
}
utils.UnknownHandlerError(c, err)
return
}
if err := common.DB.Delete(&user).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func createUserHandler(c *gin.Context) {
var user model.User
if err := c.ShouldBindJSON(&user); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
if err := common.DB.Create(&user).Error; err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
if err := checkDuplicatedFields(user); err != nil {
utils.HandlerError(c, http.StatusBadRequest, err.Error())
return
}
} else {
utils.UnknownHandlerError(c, err)
return
}
}
c.JSON(http.StatusCreated, user)
}
func updateUserHandler(c *gin.Context) {
updateUser(c, c.Param("id"))
}
func updateCurrentUserHandler(c *gin.Context) {
updateUser(c, c.GetString("userID"))
}
func createOneTimeAccessTokenHandler(c *gin.Context) {
var input model.OneTimeAccessTokenCreateDto
if err := c.ShouldBindJSON(&input); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
randomString, err := utils.GenerateRandomAlphanumericString(16)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
oneTimeAccessToken := model.OneTimeAccessToken{
UserID: input.UserID,
ExpiresAt: input.ExpiresAt,
Token: randomString,
}
if err := common.DB.Create(&oneTimeAccessToken).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{"token": oneTimeAccessToken})
}
func exchangeOneTimeAccessTokenHandler(c *gin.Context) {
var oneTimeAccessToken model.OneTimeAccessToken
if err := common.DB.Where("token = ? AND expires_at > ?", c.Param("token"), utils.FormatDateForDb(time.Now())).Preload("User").First(&oneTimeAccessToken).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.HandlerError(c, http.StatusForbidden, "Token is invalid or expired")
return
}
utils.UnknownHandlerError(c, err)
return
}
token, err := common.GenerateAccessToken(oneTimeAccessToken.User)
if err != nil {
utils.UnknownHandlerError(c, err)
log.Println(err)
return
}
if err := common.DB.Delete(&oneTimeAccessToken).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.SetCookie("access_token", token, int(time.Hour.Seconds()), "/", "", false, true)
c.JSON(http.StatusOK, oneTimeAccessToken.User)
}
// getSetupAccessTokenHandler creates the initial admin user and returns an access token for the user
// This handler is only available if there are no users in the database
func getSetupAccessTokenHandler(c *gin.Context) {
var userCount int64
if err := common.DB.Model(&model.User{}).Count(&userCount).Error; err != nil {
log.Fatal("failed to count users", err)
}
// If there are more than one user, we don't need to create the admin user
if userCount > 1 {
utils.HandlerError(c, http.StatusForbidden, "Setup already completed")
return
}
var user = model.User{
FirstName: "Admin",
LastName: "Admin",
Username: "admin",
Email: "admin@admin.com",
IsAdmin: true,
}
// Create the initial admin user if it doesn't exist
if err := common.DB.Model(&model.User{}).Preload("Credentials").FirstOrCreate(&user).Error; err != nil {
log.Fatal("failed to create admin user", err)
}
// If the user already has credentials, the setup is already completed
if len(user.Credentials) > 0 {
utils.HandlerError(c, http.StatusForbidden, "Setup already completed")
return
}
token, err := common.GenerateAccessToken(user)
if err != nil {
utils.UnknownHandlerError(c, err)
log.Println(err)
return
}
c.SetCookie("access_token", token, int(time.Hour.Seconds()), "/", "", false, true)
c.JSON(http.StatusOK, user)
}
func updateUser(c *gin.Context, userID string) {
var user model.User
if err := common.DB.Where("id = ?", userID).First(&user).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
utils.HandlerError(c, http.StatusNotFound, "User not found")
return
}
utils.UnknownHandlerError(c, err)
return
}
var updatedUser model.User
if err := c.ShouldBindJSON(&updatedUser); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
if err := common.DB.Model(&user).Updates(&updatedUser).Error; err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
if err := checkDuplicatedFields(user); err != nil {
utils.HandlerError(c, http.StatusBadRequest, err.Error())
return
}
} else {
utils.UnknownHandlerError(c, err)
return
}
}
c.JSON(http.StatusOK, updatedUser)
}
func checkDuplicatedFields(user model.User) error {
var existingUser model.User
if common.DB.Where("id != ? AND email = ?", user.ID, user.Email).First(&existingUser).Error == nil {
return errors.New("email is already taken")
}
if common.DB.Where("id != ? AND username = ?", user.ID, user.Username).First(&existingUser).Error == nil {
return errors.New("username is already taken")
}
return nil
}

View File

@@ -0,0 +1,255 @@
package handler
import (
"github.com/gin-gonic/gin"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"golang-rest-api-template/internal/common"
"golang-rest-api-template/internal/common/middleware"
"golang-rest-api-template/internal/model"
"golang-rest-api-template/internal/utils"
"golang.org/x/time/rate"
"gorm.io/gorm"
"log"
"net/http"
"strings"
"time"
)
func RegisterRoutes(group *gin.RouterGroup) {
group.GET("/webauthn/register/start", middleware.JWTAuth(false), beginRegistrationHandler)
group.POST("/webauthn/register/finish", middleware.JWTAuth(false), verifyRegistrationHandler)
group.GET("/webauthn/login/start", beginLoginHandler)
group.POST("/webauthn/login/finish", middleware.RateLimiter(rate.Every(10*time.Second), 5), verifyLoginHandler)
group.POST("/webauthn/logout", middleware.JWTAuth(false), logoutHandler)
group.GET("/webauthn/credentials", middleware.JWTAuth(false), listCredentialsHandler)
group.PATCH("/webauthn/credentials/:id", middleware.JWTAuth(false), updateCredentialHandler)
group.DELETE("/webauthn/credentials/:id", middleware.JWTAuth(false), deleteCredentialHandler)
}
func beginRegistrationHandler(c *gin.Context) {
var user model.User
err := common.DB.Preload("Credentials").Find(&user, "id = ?", c.GetString("userID")).Error
if err != nil {
utils.UnknownHandlerError(c, err)
log.Println(err)
return
}
options, session, err := common.WebAuthn.BeginRegistration(&user, webauthn.WithResidentKeyRequirement(protocol.ResidentKeyRequirementRequired), webauthn.WithExclusions(user.WebAuthnCredentialDescriptors()))
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
// Save the webauthn session so we can retrieve it in the verifyRegistrationHandler
sessionToStore := &model.WebauthnSession{
ExpiresAt: session.Expires,
Challenge: session.Challenge,
UserVerification: string(session.UserVerification),
}
if err = common.DB.Create(&sessionToStore).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.SetCookie("session_id", sessionToStore.ID, int(common.WebAuthn.Config.Timeouts.Registration.Timeout.Seconds()), "/", "", false, true)
c.JSON(http.StatusOK, options.Response)
}
func verifyRegistrationHandler(c *gin.Context) {
sessionID, err := c.Cookie("session_id")
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "Session ID missing")
return
}
// Retrieve the session that was previously created by the beginRegistrationHandler
var storedSession model.WebauthnSession
err = common.DB.First(&storedSession, "id = ?", sessionID).Error
session := webauthn.SessionData{
Challenge: storedSession.Challenge,
Expires: storedSession.ExpiresAt,
UserID: []byte(c.GetString("userID")),
}
var user model.User
err = common.DB.Find(&user, "id = ?", c.GetString("userID")).Error
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
credential, err := common.WebAuthn.FinishRegistration(&user, session, c.Request)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
credentialToStore := model.WebauthnCredential{
Name: "New Passkey",
CredentialID: string(credential.ID),
AttestationType: credential.AttestationType,
PublicKey: credential.PublicKey,
Transport: credential.Transport,
UserID: user.ID,
}
if err := common.DB.Create(&credentialToStore).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, credentialToStore)
}
func beginLoginHandler(c *gin.Context) {
options, session, err := common.WebAuthn.BeginDiscoverableLogin()
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
// Save the webauthn session so we can retrieve it in the verifyLoginHandler
sessionToStore := &model.WebauthnSession{
ExpiresAt: session.Expires,
Challenge: session.Challenge,
UserVerification: string(session.UserVerification),
}
if err = common.DB.Create(&sessionToStore).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.SetCookie("session_id", sessionToStore.ID, int(common.WebAuthn.Config.Timeouts.Registration.Timeout.Seconds()), "/", "", false, true)
c.JSON(http.StatusOK, options.Response)
}
func verifyLoginHandler(c *gin.Context) {
sessionID, err := c.Cookie("session_id")
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "Session ID missing")
return
}
credentialAssertionData, err := protocol.ParseCredentialRequestResponseBody(c.Request.Body)
if err != nil {
utils.HandlerError(c, http.StatusBadRequest, "Invalid body")
return
}
// Retrieve the session that was previously created by the beginLoginHandler
var storedSession model.WebauthnSession
if err := common.DB.First(&storedSession, "id = ?", sessionID).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
session := webauthn.SessionData{
Challenge: storedSession.Challenge,
Expires: storedSession.ExpiresAt,
}
var user *model.User
_, err = common.WebAuthn.ValidateDiscoverableLogin(func(_, userHandle []byte) (webauthn.User, error) {
if err := common.DB.Preload("Credentials").First(&user, "id = ?", string(userHandle)).Error; err != nil {
return nil, err
}
return user, nil
}, session, credentialAssertionData)
if err != nil {
if strings.Contains(err.Error(), gorm.ErrRecordNotFound.Error()) {
utils.HandlerError(c, http.StatusBadRequest, "no user with this passkey exists")
} else {
utils.UnknownHandlerError(c, err)
}
return
}
err = common.DB.Find(&user, "id = ?", c.GetString("userID")).Error
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
token, err := common.GenerateAccessToken(*user)
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.SetCookie("access_token", token, int(time.Hour.Seconds()), "/", "", false, true)
c.JSON(http.StatusOK, user)
}
func listCredentialsHandler(c *gin.Context) {
var credentials []model.WebauthnCredential
if err := common.DB.Find(&credentials, "user_id = ?", c.GetString("userID")).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, credentials)
}
func deleteCredentialHandler(c *gin.Context) {
var passkeyCount int64
if err := common.DB.Model(&model.WebauthnCredential{}).Where("user_id = ?", c.GetString("userID")).Count(&passkeyCount).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
if passkeyCount == 1 {
utils.HandlerError(c, http.StatusBadRequest, "You must have at least one passkey")
return
}
var credential model.WebauthnCredential
if err := common.DB.First(&credential, "id = ? AND user_id = ?", c.Param("id"), c.GetString("userID")).Error; err != nil {
utils.HandlerError(c, http.StatusNotFound, "Credential not found")
return
}
if err := common.DB.Delete(&credential).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func updateCredentialHandler(c *gin.Context) {
var credential model.WebauthnCredential
if err := common.DB.Where("id = ? AND user_id = ?", c.Param("id"), c.GetString("userID")).First(&credential).Error; err != nil {
utils.HandlerError(c, http.StatusNotFound, "Credential not found")
return
}
var input struct {
Name string `json:"name"`
}
if err := c.ShouldBindJSON(&input); err != nil {
utils.HandlerError(c, http.StatusBadRequest, "invalid request body")
return
}
credential.Name = input.Name
if err := common.DB.Save(&credential).Error; err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func logoutHandler(c *gin.Context) {
c.SetCookie("access_token", "", 0, "/", "", false, true)
c.Status(http.StatusNoContent)
}

View File

@@ -0,0 +1,39 @@
package handler
import (
"github.com/gin-gonic/gin"
"golang-rest-api-template/internal/common"
"golang-rest-api-template/internal/utils"
"net/http"
)
func RegisterWellKnownRoutes(group *gin.RouterGroup) {
group.GET("/.well-known/jwks.json", jwks)
group.GET("/.well-known/openid-configuration", openIDConfiguration)
}
func jwks(c *gin.Context) {
jwk, err := common.GetJWK()
if err != nil {
utils.UnknownHandlerError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"keys": []interface{}{jwk}})
}
func openIDConfiguration(c *gin.Context) {
appUrl := common.EnvConfig.AppURL
config := map[string]interface{}{
"issuer": appUrl,
"authorization_endpoint": appUrl + "/authorize",
"token_endpoint": appUrl + "/api/oidc/token",
"jwks_uri": appUrl + "/.well-known/jwks.json",
"scopes_supported": []string{"openid", "profile", "email"},
"claims_supported": []string{"sub", "given_name", "family_name", "email", "preferred_username"},
"response_types_supported": []string{"code", "id_token"},
"subject_types_supported": []string{"public"},
"id_token_signing_alg_values_supported": []string{"RS256"},
}
c.JSON(http.StatusOK, config)
}