Add login and auth
This commit is contained in:
3
.idea/inspectionProfiles/Project_Default.xml
generated
3
.idea/inspectionProfiles/Project_Default.xml
generated
@@ -4,10 +4,11 @@
|
||||
<inspection_tool class="HtmlUnknownAttribute" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="myValues">
|
||||
<value>
|
||||
<list size="3">
|
||||
<list size="4">
|
||||
<item index="0" class="java.lang.String" itemvalue="hx-get" />
|
||||
<item index="1" class="java.lang.String" itemvalue="hx-target" />
|
||||
<item index="2" class="java.lang.String" itemvalue="hx-vals" />
|
||||
<item index="3" class="java.lang.String" itemvalue="hx-post" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
|
||||
2
go.mod
2
go.mod
@@ -17,6 +17,8 @@ require (
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/gorilla/sessions v1.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
|
||||
4
go.sum
4
go.sum
@@ -27,6 +27,10 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaS
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
||||
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
||||
github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
|
||||
github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
|
||||
209
main.go
209
main.go
@@ -4,17 +4,27 @@ import (
|
||||
"InfrantrySkillCalculator/controllers"
|
||||
"InfrantrySkillCalculator/models"
|
||||
"InfrantrySkillCalculator/utils"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/sessions"
|
||||
_ "github.com/gorilla/sessions"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
var store = sessions.NewCookieStore([]byte("f0q0qew0!)§(ds9713lsda231"))
|
||||
|
||||
func main() {
|
||||
//gin.SetMode(gin.ReleaseMode) // uncomment upon release
|
||||
|
||||
router := gin.New()
|
||||
router.LoadHTMLGlob("templates/**/*")
|
||||
protected := router.Group("/")
|
||||
protected.Use(AuthRequired())
|
||||
|
||||
models.ConnectDatabase()
|
||||
|
||||
@@ -27,55 +37,164 @@ func main() {
|
||||
|
||||
router.Static("/static", "./static")
|
||||
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
files := []string{
|
||||
"./templates/index.html",
|
||||
"./templates/components/home_clan_bar.html",
|
||||
"./templates/components/opp_clan_bar.html",
|
||||
"./templates/components/home_player_list.html",
|
||||
"./templates/components/opp_player_list.html",
|
||||
"./templates/components/bottom_controls.html",
|
||||
"./templates/modals/delete_clan.html",
|
||||
"./templates/modals/add_clan.html",
|
||||
"./templates/modals/edit_clan.html",
|
||||
"./templates/modals/add_player.html",
|
||||
"./templates/modals/delete_player.html",
|
||||
"./templates/modals/edit_player.html",
|
||||
"./templates/components/header.html",
|
||||
}
|
||||
tmpl, err := template.ParseFiles(files...)
|
||||
router.GET("/login", loginPage)
|
||||
router.POST("/login", loginPost)
|
||||
router.GET("/logout", logout)
|
||||
|
||||
var clans []models.Clan
|
||||
models.DB.Find(&clans)
|
||||
protected.GET("/", mainPage)
|
||||
|
||||
data := map[string]interface{}{
|
||||
"clans": clans,
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
protected.GET("/clans", controllers.GetAllClans)
|
||||
protected.GET("/clans_html", controllers.GetAllClansHTML)
|
||||
protected.GET("/clan/:id", controllers.GetClanByID)
|
||||
protected.POST("/clan", controllers.AddClan)
|
||||
protected.PATCH("/clan/:id", controllers.UpdateClanByID)
|
||||
protected.DELETE("/clan/:id", controllers.DeleteClanByID)
|
||||
|
||||
err = tmpl.Execute(c.Writer, data)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
})
|
||||
|
||||
router.GET("/clans", controllers.GetAllClans)
|
||||
router.GET("/clans_html", controllers.GetAllClansHTML)
|
||||
router.GET("/clan/:id", controllers.GetClanByID)
|
||||
router.POST("/clan", controllers.AddClan)
|
||||
router.PATCH("/clan/:id", controllers.UpdateClanByID)
|
||||
router.DELETE("/clan/:id", controllers.DeleteClanByID)
|
||||
|
||||
router.GET("/players", controllers.GetAllPlayers)
|
||||
router.GET("/players_html", controllers.GetPlayersByClanHTML)
|
||||
router.GET("/player/:id", controllers.GetPlayerByID)
|
||||
router.GET("/playerid/:name", controllers.GetPlayerIDByName)
|
||||
router.POST("/player", controllers.AddPlayer)
|
||||
router.PATCH("/player/:id", controllers.UpdatePlayerByID)
|
||||
router.DELETE("/player/:id", controllers.DeletePlayerByID)
|
||||
protected.GET("/players", controllers.GetAllPlayers)
|
||||
protected.GET("/players_html", controllers.GetPlayersByClanHTML)
|
||||
protected.GET("/player/:id", controllers.GetPlayerByID)
|
||||
protected.GET("/playerid/:name", controllers.GetPlayerIDByName)
|
||||
protected.POST("/player", controllers.AddPlayer)
|
||||
protected.PATCH("/player/:id", controllers.UpdatePlayerByID)
|
||||
protected.DELETE("/player/:id", controllers.DeletePlayerByID)
|
||||
|
||||
log.Println("Running on 8000...")
|
||||
log.Fatal(router.Run(":8000"))
|
||||
}
|
||||
|
||||
func mainPage(c *gin.Context) {
|
||||
files := []string{
|
||||
"./templates/index.html",
|
||||
"./templates/components/home_clan_bar.html",
|
||||
"./templates/components/opp_clan_bar.html",
|
||||
"./templates/components/home_player_list.html",
|
||||
"./templates/components/opp_player_list.html",
|
||||
"./templates/components/bottom_controls.html",
|
||||
"./templates/modals/delete_clan.html",
|
||||
"./templates/modals/add_clan.html",
|
||||
"./templates/modals/edit_clan.html",
|
||||
"./templates/modals/add_player.html",
|
||||
"./templates/modals/delete_player.html",
|
||||
"./templates/modals/edit_player.html",
|
||||
"./templates/components/header.html",
|
||||
}
|
||||
tmpl, err := template.ParseFiles(files...)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var clans []models.Clan
|
||||
models.DB.Find(&clans)
|
||||
|
||||
data := map[string]interface{}{
|
||||
"clans": clans,
|
||||
}
|
||||
|
||||
err = tmpl.Execute(c.Writer, data)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func loginPage(c *gin.Context) {
|
||||
session, _ := store.Get(c.Request, "session-name")
|
||||
|
||||
if auth, ok := session.Values["authenticated"].(bool); ok && auth {
|
||||
c.Redirect(http.StatusFound, "/")
|
||||
return
|
||||
}
|
||||
|
||||
tmpl, err := template.ParseFiles([]string{"./templates/login.html", "./templates/components/header.html"}...)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
err = tmpl.Execute(c.Writer, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func loginPost(c *gin.Context) {
|
||||
username := c.PostForm("username")
|
||||
password := c.PostForm("password")
|
||||
|
||||
if !checkUserCredentials(username, password) {
|
||||
c.HTML(http.StatusOK, "login_error.html", gin.H{"message": "Ungültige Logindaten!"})
|
||||
return
|
||||
}
|
||||
|
||||
session, _ := store.Get(c.Request, "session-name")
|
||||
session.Values["authenticated"] = true
|
||||
session.Values["username"] = username
|
||||
err := session.Save(c.Request, c.Writer)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, nil)
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("HX-Redirect", "/")
|
||||
c.String(http.StatusOK, "")
|
||||
}
|
||||
|
||||
func checkUserCredentials(username, password string) bool {
|
||||
var hashedPassword string
|
||||
|
||||
hashedPassword, err := getUserPassword(username)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func getUserPassword(username string) (string, error) {
|
||||
var user models.User
|
||||
|
||||
if err := models.DB.Where("username = ?", username).First(&user).Error; err != nil {
|
||||
log.Fatal(err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
var hashedPW string
|
||||
hashedPW, err := hashPassword(user.Password)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hashedPW, nil
|
||||
}
|
||||
|
||||
func logout(c *gin.Context) {
|
||||
session, _ := store.Get(c.Request, "session-name")
|
||||
session.Values["authenticated"] = false
|
||||
err := session.Save(c.Request, c.Writer)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, nil)
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(http.StatusFound, "/login")
|
||||
}
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to hash password: %w", err)
|
||||
}
|
||||
return string(hashedPassword), nil
|
||||
}
|
||||
|
||||
func AuthRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
session, _ := store.Get(c.Request, "session-name")
|
||||
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
|
||||
c.Redirect(http.StatusFound, "/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
7
models/user.go
Normal file
7
models/user.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package models
|
||||
|
||||
type User struct {
|
||||
Username string `json:"username" gorm:"primary_key"`
|
||||
Password string `json:"password"`
|
||||
Enabled bool `json:"enabled" default:"1"`
|
||||
}
|
||||
3
templates/components/login_error.html
Normal file
3
templates/components/login_error.html
Normal file
@@ -0,0 +1,3 @@
|
||||
<div class="text-danger">
|
||||
{{ .message }}
|
||||
</div>
|
||||
24
templates/login.html
Normal file
24
templates/login.html
Normal file
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
{{ template "header" . }}
|
||||
</head>
|
||||
<body data-bs-theme="dark" class="h-auto">
|
||||
<div class="container-fluid bg-dark mt-5 p-4 rounded-3 text-light text-center" style="max-width: 500px;">
|
||||
<h3>Login</h3>
|
||||
<hr>
|
||||
<form hx-post="/login" hx-target="#login-result">
|
||||
<div class="form-floating mb-3">
|
||||
<input class="form-control form-control-lg" type="text" id="username" name="username" placeholder="Username" required>
|
||||
<label for="username">Username</label>
|
||||
</div>
|
||||
<div class="form-floating">
|
||||
<input class="form-control form-control-lg" type="password" id="password" name="password" placeholder="Passwort" required>
|
||||
<label for="password">Passwort</label>
|
||||
</div>
|
||||
<button class="btn btn-lg btn-primary mt-3" type="submit">Anmelden</button>
|
||||
</form>
|
||||
<div id="login-result" class="mt-4 fs-4"></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user