user.go 2.88 KB
package main

import (
	"context"
	"encoding/json"
	"net/http"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/go-sql-driver/mysql"
	"golang.org/x/crypto/sha3"
)

type User struct {
	No        uint64    `json:"no"`
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	ExpiredAt time.Time `json:"expired_at"`
}

func (app *App) PostUsers(w http.ResponseWriter, r *http.Request) {
	body := make(map[string]interface{})
	err := json.NewDecoder(r.Body).Decode(&body)
	if err != nil {
		WriteError(w, http.StatusBadRequest, "Failed to parse request json")
		return
	}

	hash := sha3.Sum256([]byte(body["password"].(string)))

	res, err := app.db.Exec("INSERT INTO users (`id`, `password`, `name`) VALUES (?, ?, ?)", body["id"], hash[:], body["name"])
	if err != nil {
		if merr, ok := err.(*mysql.MySQLError); ok {
			if merr.Number == 1062 {
				WriteError(w, http.StatusConflict, "Already registered")
				return
			}
		}

		WriteError(w, http.StatusInternalServerError, "Failed to register")
		return
	}

	no, _ := res.LastInsertId()
	WriteJson(w, map[string]interface{}{"user_no": no})
}

type AuthClaims struct {
	UserNo uint64 `json:"user_no"`
	jwt.StandardClaims
}

func (app *App) PostTokens(w http.ResponseWriter, r *http.Request) {
	body := make(map[string]interface{})
	err := json.NewDecoder(r.Body).Decode(&body)
	if err != nil {
		WriteError(w, http.StatusBadRequest, "Failed to parse request json")
		return
	}

	hash := sha3.Sum256([]byte(body["password"].(string)))
	rows, err := app.db.Query("SELECT `no` FROM users WHERE `id`=? AND `password`=?", body["id"], hash[:])
	if err != nil {
		WriteError(w, http.StatusInternalServerError, "Failed to register")
		return
	}

	if !rows.Next() {
		WriteError(w, http.StatusUnauthorized, "Login failed")
		return
	}

	no := uint64(0)
	rows.Scan(&no)

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, AuthClaims{UserNo: no})
	auth, err := token.SignedString([]byte(app.Config.TokenSecret))
	if err != nil {
		WriteError(w, http.StatusInternalServerError, "Login failed")
		return
	}

	WriteJson(w, map[string]interface{}{"token": auth})
}

func (app *App) WithAuth(next func(http.ResponseWriter, *http.Request)) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		auth := r.Header.Get("Authorization")
		if len(auth) > 6 && strings.Index(auth, "Bearer ") == 0 {
			token, err := jwt.ParseWithClaims(auth[7:], &AuthClaims{}, func(token *jwt.Token) (interface{}, error) {
				return []byte(app.Config.TokenSecret), nil
			})

			if err == nil {
				claims := token.Claims.(*AuthClaims)
				ctx := context.WithValue(r.Context(), PropUserNo, claims.UserNo)
				next(w, r.WithContext(ctx))
				return
			}
		}

		WriteError(w, http.StatusUnauthorized, "Authorization failed")
	})
}