85 lines
2.1 KiB
Go
85 lines
2.1 KiB
Go
|
package auth
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"database/sql"
|
||
|
"encoding/json"
|
||
|
"github.com/dgrijalva/jwt-go"
|
||
|
"github.com/go-chi/chi"
|
||
|
"github.com/go-chi/jwtauth"
|
||
|
"github.com/go-chi/render"
|
||
|
"golang.org/x/crypto/bcrypt"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
DB *sql.DB
|
||
|
TokenAuth *jwtauth.JWTAuth
|
||
|
)
|
||
|
|
||
|
type Credentials struct {
|
||
|
Password string `json:"password", db:"password"`
|
||
|
Username string `json:"username", db:"username"`
|
||
|
}
|
||
|
|
||
|
func Init() {
|
||
|
DB.Exec("CREATE TABLE IF NOT EXISTS users (username text primary key, password text, admin boolean);" )
|
||
|
}
|
||
|
|
||
|
func Routes() *chi.Mux {
|
||
|
router := chi.NewRouter()
|
||
|
router.Post("/signin", Signin)
|
||
|
router.Post("/signup", Signup)
|
||
|
return router
|
||
|
}
|
||
|
|
||
|
func Signup(w http.ResponseWriter, r *http.Request) {
|
||
|
creds := &Credentials{}
|
||
|
err := json.NewDecoder(r.Body).Decode(creds)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 10)
|
||
|
s := `INSERT INTO users (username, password, admin)
|
||
|
VALUES ($1, $2, $3)`
|
||
|
if _, err = DB.Exec(s, creds.Username, string(hashedPassword), false); err != nil {
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
fmt.Println(err)
|
||
|
return
|
||
|
}
|
||
|
w.WriteHeader(http.StatusCreated)
|
||
|
}
|
||
|
|
||
|
func Signin(w http.ResponseWriter, r *http.Request) {
|
||
|
creds := &Credentials{}
|
||
|
err := json.NewDecoder(r.Body).Decode(creds)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
result := DB.QueryRow("SELECT password FROM users WHERE username=$1", creds.Username)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
storedCreds := &Credentials{}
|
||
|
err = result.Scan(&storedCreds.Password)
|
||
|
if err != nil {
|
||
|
if err == sql.ErrNoRows {
|
||
|
w.WriteHeader(http.StatusUnauthorized)
|
||
|
return
|
||
|
}
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil {
|
||
|
w.WriteHeader(http.StatusUnauthorized)
|
||
|
}
|
||
|
_, tokenString, _ := TokenAuth.Encode(jwt.MapClaims{
|
||
|
"username": creds.Username,
|
||
|
})
|
||
|
w.WriteHeader(http.StatusOK)
|
||
|
render.JSON(w, r, tokenString)
|
||
|
}
|