Return JWT after register/login, .env file support

for JWT_SECRET
This commit is contained in:
IRHM
2023-03-20 23:35:36 +00:00
parent a4068ed289
commit a8be0567e6
4 changed files with 54 additions and 2 deletions
+32 -2
View File
@@ -8,8 +8,10 @@ import (
"errors"
"fmt"
"log"
"os"
"strings"
"github.com/golang-jwt/jwt/v5"
"github.com/uptrace/bun"
"golang.org/x/crypto/argon2"
)
@@ -60,7 +62,19 @@ func register(user *User, db *bun.DB) (RegisterResponse, error) {
panic(err)
}
return RegisterResponse{Token: "My JWT token"}, nil
// Bun fills our user obj with the ID from db after insert,
// just ensure it actually has.
if user.ID == 0 {
fmt.Println("user.ID not filled out after registration", user.ID)
return RegisterResponse{}, errors.New("failed to get user id, try login")
}
token, err := signJWT(user)
if err != nil {
fmt.Println("Failed to sign new jwt:", err)
return RegisterResponse{}, errors.New("failed to get auth token")
}
return RegisterResponse{Token: token}, nil
}
func login(user *User, db *bun.DB) (RegisterResponse, error) {
@@ -83,7 +97,23 @@ func login(user *User, db *bun.DB) (RegisterResponse, error) {
return RegisterResponse{}, errors.New("incorrect details")
}
return RegisterResponse{Token: "My JWT token"}, nil
token, err := signJWT(dbUser)
if err != nil {
fmt.Println("Failed to sign new jwt:", err)
return RegisterResponse{}, errors.New("failed to get auth token")
}
return RegisterResponse{Token: token}, nil
}
func signJWT(user *User) (token string, err error) {
// Create new jwt with claim data
jwt := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"userId": user.ID,
"username": user.Username,
})
// Sign and get the complete encoded token as a string using the secret
return jwt.SignedString([]byte(os.Getenv("JWT_SECRET")))
}
func hashPassword(password string, p *ArgonParams) (encodedHash string, err error) {
+2
View File
@@ -4,6 +4,8 @@ go 1.20
require (
github.com/gin-gonic/gin v1.9.0
github.com/golang-jwt/jwt/v5 v5.0.0-rc.1
github.com/joho/godotenv v1.5.1
github.com/uptrace/bun v1.1.12
github.com/uptrace/bun/dialect/sqlitedialect v1.1.12
github.com/uptrace/bun/driver/sqliteshim v1.1.12
+4
View File
@@ -22,6 +22,8 @@ github.com/go-playground/validator/v10 v10.11.2 h1:q3SHpufmypg+erIExEKUmsgmhDTyh
github.com/go-playground/validator/v10 v10.11.2/go.mod h1:NieE624vt4SCTJtD87arVLvdmjPAeV8BQlHtMnw9D7s=
github.com/goccy/go-json v0.10.0 h1:mXKd9Qw4NuzShiRlOXKews24ufknHO7gx30lsDyokKA=
github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 h1:tDQ1LjKga657layZ4JLsRdxgvupebc0xuPwRNuTfUgs=
github.com/golang-jwt/jwt/v5 v5.0.0-rc.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
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=
@@ -29,6 +31,8 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
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/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
+16
View File
@@ -4,8 +4,11 @@ import (
"context"
"database/sql"
"fmt"
"log"
"os"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/sqlitedialect"
"github.com/uptrace/bun/driver/sqliteshim"
@@ -14,6 +17,12 @@ import (
func main() {
fmt.Println("Watcharr Starting")
err := godotenv.Load()
if err != nil {
panic("Failed to load vars from .env file")
}
ensureEnv()
sqldb, err := sql.Open(sqliteshim.ShimName, "./watcharr.db")
if err != nil {
panic(err)
@@ -32,3 +41,10 @@ func main() {
gin.Run("localhost:3080")
}
// Ensure all required environment variables are set.
func ensureEnv() {
if os.Getenv("JWT_SECRET") == "" {
log.Fatal("JWT_SECRET env var missing!")
}
}