This repository has been archived on 2023-07-09. You can view files and clone it, but cannot push or open issues or pull requests.
sudoscientist-go-backend/packages/auth/auth.go

87 lines
2.2 KiB
Go
Raw Normal View History

2019-02-03 06:57:08 +00:00
package auth
import (
"fmt"
"database/sql"
"encoding/json"
2019-02-07 04:46:30 +00:00
"git.minhas.io/asara/sudoscientist/packages/users"
2019-02-03 06:57:08 +00:00
"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 {
Username string `json:"username", db:"username"`
2019-02-07 04:46:30 +00:00
Password string `json:"password", db:"password"`
2019-02-03 06:57:08 +00:00
}
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()
2019-02-08 04:43:26 +00:00
router.Post("/signin", signin)
router.Post("/signup", signup)
2019-02-03 06:57:08 +00:00
return router
}
2019-02-08 04:43:26 +00:00
func signup(w http.ResponseWriter, r *http.Request) {
2019-02-03 06:57:08 +00:00
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
}
2019-02-07 04:46:30 +00:00
users.CreateProfile(creds.Username)
2019-02-03 06:57:08 +00:00
w.WriteHeader(http.StatusCreated)
}
2019-02-08 04:43:26 +00:00
func signin(w http.ResponseWriter, r *http.Request) {
2019-02-03 06:57:08 +00:00
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)
}