first commit
This commit is contained in:
167
internal/jwtcontroller/accounts.go
Normal file
167
internal/jwtcontroller/accounts.go
Normal file
@ -0,0 +1,167 @@
|
||||
package jwtcontroller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
|
||||
"strings"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
|
||||
"os"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
/*
|
||||
JWT claims struct
|
||||
*/
|
||||
type Token struct {
|
||||
UserId uint
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
//a struct to rep user account
|
||||
type Account struct {
|
||||
gorm.Model
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Token string `json:"token";sql:"-"`
|
||||
}
|
||||
|
||||
//Validate incoming user details...
|
||||
func (account *Account) Validate() (map[string]interface{}, bool) {
|
||||
|
||||
if !strings.Contains(account.Email, "@") {
|
||||
return Message(false, "Email address is required"), false
|
||||
}
|
||||
|
||||
if len(account.Password) < 1 {
|
||||
return Message(false, "Password is required"), false
|
||||
}
|
||||
|
||||
//Email must be unique
|
||||
temp := &Account{}
|
||||
|
||||
//check for errors and duplicate emails
|
||||
err := GetDB().Table("accounts").Where("email = ?", account.Email).First(temp).Error
|
||||
if err != nil && err != gorm.ErrRecordNotFound {
|
||||
return Message(false, "Connection error. Please retry"), false
|
||||
}
|
||||
if temp.Email != "" {
|
||||
return Message(false, "Email address already in use by another user."), false
|
||||
}
|
||||
|
||||
return Message(false, "Requirement passed"), true
|
||||
}
|
||||
|
||||
func (account *Account) Create() map[string]interface{} {
|
||||
|
||||
if resp, ok := account.Validate(); !ok {
|
||||
return resp
|
||||
}
|
||||
|
||||
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(account.Password), bcrypt.DefaultCost)
|
||||
account.Password = string(hashedPassword)
|
||||
|
||||
GetDB().Create(account)
|
||||
|
||||
if account.ID <= 0 {
|
||||
return Message(false, "Failed to create account, connection error.")
|
||||
}
|
||||
|
||||
//Create new JWT token for the newly registered account
|
||||
tk := &Token{UserId: account.ID}
|
||||
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
|
||||
tokenString, _ := token.SignedString([]byte(os.Getenv("token_password")))
|
||||
account.Token = tokenString
|
||||
|
||||
account.Password = "" //delete password
|
||||
|
||||
response := Message(true, "Account has been created")
|
||||
response["account"] = account
|
||||
return response
|
||||
}
|
||||
|
||||
func Login(email, password string) map[string]interface{} {
|
||||
|
||||
account := &Account{}
|
||||
err := GetDB().Table("accounts").Where("email = ?", email).First(account).Error
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return Message(false, "Email address not found")
|
||||
}
|
||||
return Message(false, "Connection error. Please retry")
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(password))
|
||||
if err != nil && err == bcrypt.ErrMismatchedHashAndPassword { //Password does not match!
|
||||
return Message(false, "Invalid login credentials. Please try again")
|
||||
}
|
||||
//Worked! Logged In
|
||||
account.Password = ""
|
||||
|
||||
//Create JWT token
|
||||
tk := &Token{UserId: account.ID}
|
||||
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
|
||||
tokenString, _ := token.SignedString([]byte(os.Getenv("token_password")))
|
||||
account.Token = tokenString //Store the token in the response
|
||||
|
||||
resp := Message(true, "Logged In")
|
||||
resp["account"] = account
|
||||
return resp
|
||||
}
|
||||
|
||||
func GetUser(u uint) *Account {
|
||||
|
||||
acc := &Account{}
|
||||
GetDB().Table("accounts").Where("id = ?", u).First(acc)
|
||||
if acc.Email == "" { //User not found!
|
||||
return nil
|
||||
}
|
||||
|
||||
acc.Password = ""
|
||||
return acc
|
||||
}
|
||||
|
||||
var CreateAccount = func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
account := &Account{}
|
||||
err := json.NewDecoder(r.Body).Decode(account) //decode the request body into struct and failed if any error occur
|
||||
log.Println(err)
|
||||
if err != nil {
|
||||
Respond(w, Message(false, "Invalid request"))
|
||||
return
|
||||
}
|
||||
|
||||
resp := account.Create() //Create account
|
||||
Respond(w, resp)
|
||||
}
|
||||
|
||||
var Authenticate = func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
account := &Account{}
|
||||
err := json.NewDecoder(r.Body).Decode(account) //decode the request body into struct and failed if any error occur
|
||||
log.Println(err)
|
||||
if err != nil {
|
||||
Respond(w, Message(false, "Invalid request"))
|
||||
return
|
||||
}
|
||||
|
||||
resp := Login(account.Email, account.Password)
|
||||
Respond(w, resp)
|
||||
}
|
||||
|
||||
func Message(status bool, message string) map[string]interface{} {
|
||||
log.Println(message)
|
||||
return map[string]interface{}{"status": status, "message": message}
|
||||
}
|
||||
|
||||
func Respond(w http.ResponseWriter, data map[string]interface{}) {
|
||||
log.Println(data)
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
81
internal/jwtcontroller/jwt.go
Normal file
81
internal/jwtcontroller/jwt.go
Normal file
@ -0,0 +1,81 @@
|
||||
package jwtcontroller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
// JwtAuthentication is a Jwt Auth controller with postgres database
|
||||
var JwtAuthentication = func(next http.Handler) http.Handler {
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
notAuth := []string{"/api/user/new", "/api/user/login"} //List of endpoints that doesn't require auth
|
||||
requestPath := r.URL.Path //current request path
|
||||
|
||||
//check if request does not need authentication, serve the request if it doesn't need it
|
||||
for _, value := range notAuth {
|
||||
|
||||
if value == requestPath {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
response := make(map[string]interface{})
|
||||
tokenHeader := r.Header.Get("Authorization") //Grab the token from the header
|
||||
|
||||
if tokenHeader == "" { //Token is missing, returns with error code 403 Unauthorized
|
||||
response = Message(false, "Missing auth token")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
Respond(w, response)
|
||||
return
|
||||
}
|
||||
|
||||
splitted := strings.Split(tokenHeader, " ") //The token normally comes in format `Bearer {token-body}`, we check if the retrieved token matched this requirement
|
||||
if len(splitted) != 2 {
|
||||
response = Message(false, "Invalid/Malformed auth token")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
Respond(w, response)
|
||||
return
|
||||
}
|
||||
|
||||
tokenPart := splitted[1] //Grab the token part, what we are truly interested in
|
||||
tk := &Token{}
|
||||
log.Println(splitted)
|
||||
token, err := jwt.ParseWithClaims(tokenPart, tk, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(os.Getenv("token_password")), nil
|
||||
})
|
||||
|
||||
if err != nil { //Malformed token, returns with http code 403 as usual
|
||||
response = Message(false, "Malformed authentication token")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
Respond(w, response)
|
||||
return
|
||||
}
|
||||
|
||||
if !token.Valid { //Token is invalid, maybe not signed on this server
|
||||
response = Message(false, "Token is not valid.")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
Respond(w, response)
|
||||
return
|
||||
}
|
||||
|
||||
//Everything went well, proceed with the request and set the caller to the user retrieved from the parsed token
|
||||
fmt.Sprintf("User %", tk) //Useful for monitoring
|
||||
ctx := context.WithValue(r.Context(), "user", tk.UserId)
|
||||
r = r.WithContext(ctx)
|
||||
next.ServeHTTP(w, r) //proceed in the middleware chain!
|
||||
})
|
||||
}
|
41
internal/jwtcontroller/postgres.go
Normal file
41
internal/jwtcontroller/postgres.go
Normal file
@ -0,0 +1,41 @@
|
||||
package jwtcontroller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
_ "github.com/jinzhu/gorm/dialects/postgres"
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
var db *gorm.DB //database
|
||||
|
||||
func init() {
|
||||
|
||||
e := godotenv.Load() //Load .env file
|
||||
if e != nil {
|
||||
fmt.Print(e)
|
||||
}
|
||||
|
||||
username := os.Getenv("db_user")
|
||||
password := os.Getenv("db_pass")
|
||||
dbName := os.Getenv("db_name")
|
||||
dbHost := os.Getenv("db_host")
|
||||
|
||||
dbUri := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbName, password) //Build connection string
|
||||
fmt.Println(dbUri)
|
||||
|
||||
conn, err := gorm.Open("postgres", dbUri)
|
||||
if err != nil {
|
||||
fmt.Print(err)
|
||||
}
|
||||
|
||||
db = conn
|
||||
db.Debug().AutoMigrate(&Account{}) //Database migration
|
||||
}
|
||||
|
||||
//returns a handle to the DB object
|
||||
func GetDB() *gorm.DB {
|
||||
return db
|
||||
}
|
29
internal/router/router.go
Normal file
29
internal/router/router.go
Normal file
@ -0,0 +1,29 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"forges.cadoles.com/go-jwtserver/internal/jwtcontroller"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
)
|
||||
|
||||
func InitializeRouter() chi.Router {
|
||||
r := chi.NewRouter()
|
||||
// Define base middlewares
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.Logger)
|
||||
r.Use(middleware.Recoverer)
|
||||
r.Use(middleware.URLFormat)
|
||||
|
||||
r.Use(middleware.Timeout(60 * time.Second))
|
||||
|
||||
r.Route("/api/", func(r chi.Router) {
|
||||
// Middleware routes
|
||||
r.Post("/user/new", jwtcontroller.CreateAccount)
|
||||
r.Post("/user/login", jwtcontroller.Authenticate)
|
||||
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
Reference in New Issue
Block a user