Ma Suhyeon

Implement user API

# Created by https://www.toptal.com/developers/gitignore/api/go,vscode
# Edit at https://www.toptal.com/developers/gitignore?templates=go,vscode
### Go ###
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
### Go Patch ###
/vendor/
/Godeps/
### vscode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# End of https://www.toptal.com/developers/gitignore/api/go,vscode
__debug_bin
config.json
\ No newline at end of file
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type App struct {
Config Config
db *sqlx.DB
router *mux.Router
}
func NewApp(config Config) *App {
app := new(App)
app.Config = config
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s", config.Database.User, config.Database.Password, config.Database.Host, config.Database.Name)
app.db = sqlx.MustOpen("mysql", dsn)
app.router = mux.NewRouter()
app.router.HandleFunc("/users", app.PostUsers).Methods("POST")
app.router.HandleFunc("/users/tokens", app.PostTokens).Methods("POST")
return app
}
func (app *App) Serve() {
http.ListenAndServe(fmt.Sprintf(":%d", app.Config.Port), app.router)
}
package main
import (
"encoding/json"
"io/ioutil"
)
type Config struct {
Port int `json:"port"`
Database struct {
Host string `json:"host"`
Name string `json:"name"`
User string `json:"user"`
Password string `json:"password"`
} `json:"database"`
TokenSecret string `json:"token_secret"`
}
func LoadConfig(path string) (Config, error) {
config := Config{}
data, err := ioutil.ReadFile(path)
if err == nil {
err = json.Unmarshal(data, &config)
}
return config, err
}
module mf-server
go 1.15
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-sql-driver/mysql v1.5.0
github.com/gorilla/mux v1.8.0
github.com/jmoiron/sqlx v1.2.0
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897
)
github.com/dgrijalva/jwt-go v1.0.2 h1:KPldsxuKGsS2FPWsNeg9ZO18aCrGKujPoWXn2yo+KQM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA=
github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks=
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 h1:pLI5jrR7OSLijeIDcmRxNmw2api+jEfxLoykJVice/E=
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
package main
import (
"log"
)
func main() {
config, err := LoadConfig("config.json")
if err != nil {
log.Fatal(err)
}
app := NewApp(config)
app.Serve()
}
package main
import (
"encoding/json"
"net/http"
"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 {
WriteJson(w, http.StatusBadRequest, map[string]interface{}{"msg": "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 {
WriteJson(w, http.StatusConflict, map[string]interface{}{"msg": "Already registered"})
return
}
}
WriteJson(w, http.StatusInternalServerError, map[string]interface{}{"msg": "Failed to register"})
return
}
no, _ := res.LastInsertId()
WriteJson(w, http.StatusOK, map[string]interface{}{"user_no": no})
}
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 {
WriteJson(w, http.StatusBadRequest, map[string]interface{}{"msg": "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 {
WriteJson(w, http.StatusInternalServerError, map[string]interface{}{"msg": "Failed to register"})
return
}
if !rows.Next() {
WriteJson(w, http.StatusUnauthorized, map[string]interface{}{"msg": "Login failed"})
return
}
no := uint64(0)
rows.Scan(&no)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"no": no})
auth, err := token.SignedString([]byte(app.Config.TokenSecret))
if err != nil {
WriteJson(w, http.StatusInternalServerError, map[string]interface{}{"msg": "Login failed"})
return
}
WriteJson(w, http.StatusOK, map[string]interface{}{"token": auth})
}
package main
import (
"encoding/json"
"net/http"
)
func WriteJson(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(data)
}