Interrupt the execution of functions if the user is not authorized

This commit is contained in:
Ivan R. 2023-04-09 10:41:21 +05:00
parent c92fa6e9e0
commit 16095e0254
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
2 changed files with 28 additions and 10 deletions

26
main.go
View file

@ -22,7 +22,10 @@ func main() {
// Main page
r.GET("/", func(c *gin.Context) {
views.RequireAuth(c, db)
if err := views.RequireAuth(c, db); err != nil {
return
}
groups, err := backend.GetGroups(db)
if err != nil {
views.ShowError(c, err)
@ -35,7 +38,10 @@ func main() {
// Settings
r.GET("/settings", func(c *gin.Context) {
views.RequireAuth(c, db)
if err := views.RequireAuth(c, db); err != nil {
return
}
groups, err := backend.GetGroups(db)
if err != nil {
views.ShowError(c, err)
@ -91,7 +97,9 @@ func main() {
// Create new group
r.POST("/groups", func(c *gin.Context) {
views.RequireAuth(c, db)
if err := views.RequireAuth(c, db); err != nil {
return
}
groupName := c.PostForm("groupName")
_, err := backend.CreateGroup(db, groupName)
@ -106,7 +114,9 @@ func main() {
// Create new link
r.POST("/links", func(c *gin.Context) {
views.RequireAuth(c, db)
if err := views.RequireAuth(c, db); err != nil {
return
}
linkName := c.PostForm("linkName")
href := c.PostForm("href")
@ -128,7 +138,9 @@ func main() {
// Update link
r.POST("/links/:id/put", func(c *gin.Context) {
views.RequireAuth(c, db)
if err := views.RequireAuth(c, db); err != nil {
return
}
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
@ -150,7 +162,9 @@ func main() {
// Delete link
r.POST("/links/:id/delete", func(c *gin.Context) {
views.RequireAuth(c, db)
if err := views.RequireAuth(c, db); err != nil {
return
}
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {

View file

@ -1,6 +1,7 @@
package views
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/ordinary-dev/phoenix/backend"
"gorm.io/gorm"
@ -26,9 +27,10 @@ func ShowLoginForm(c *gin.Context) {
}
// Requires the user to log in before viewing the page.
// If successful, does nothing.
// In case of an error, it shows the login page or the error page.
func RequireAuth(c *gin.Context, db *gorm.DB) {
// Returns error if the user is not authorized.
// If `nil` is returned instead of an error, it is safe to display protected content.
func RequireAuth(c *gin.Context, db *gorm.DB) error {
number_of_accounts := backend.CountAdmins(db)
// First run
@ -41,12 +43,14 @@ func RequireAuth(c *gin.Context, db *gorm.DB) {
// Anonymous visitor
if err != nil {
ShowLoginForm(c)
return
return errors.New("User is not authorized")
}
err = backend.ValidateToken(db, tokenValue)
if err != nil {
ShowError(c, err)
return
return errors.New("Access token is invalid")
}
return nil
}