Compare commits

..

No commits in common. "35801f5ee92c6d3785f97577b26e13dce7a92cbc" and "513b563728e941c6ca89ede6c3af2f738d1353ce" have entirely different histories.

19 changed files with 169 additions and 285 deletions

View File

@ -13,15 +13,15 @@ func init() {
} }
func main() { func main() {
// 加载配置
config.SetupConfig()
// 初始化数据库 // 初始化数据库
err := dao.Conn() err := dao.Conn()
if err != nil { if err != nil {
golog.Fatal("数据库初始化失败: ", err) golog.Fatal("数据库初始化失败: ", err)
} }
// 加载配置
config.SetupConfig()
// 启动服务 // 启动服务
app := router.Router() app := router.Router()
app.Run(iris.Addr(":8080")) app.Run(iris.Addr(":8080"))

32
model/user.go Normal file
View File

@ -0,0 +1,32 @@
package model
import (
"drive-linked/pkg/dao"
)
type User struct {
Id int64 `json:"id,string"`
Name string `json:"name"`
Nickname string `json:"nickname"`
Email string `json:"email"`
Password string `json:"-"`
Status int32 `json:"status"`
Avatar string `json:"avatar"`
Roles string `json:"roles"`
}
func (user *User) GetByName(name string) (err error) {
err = dao.DB.Get(user, "SELECT * FROM users WHERE name=?", name)
if err != nil {
return err
}
return nil
}
func (user *User) GetByEmail(email string) (err error) {
err = dao.DB.Get(user, "SELECT * FROM users WHERE email=?", email)
if err != nil {
return err
}
return nil
}

30
model/user_test.go Normal file
View File

@ -0,0 +1,30 @@
package model
import (
"database/sql"
"drive-linked/pkg/dao"
"testing"
)
func init() {
err := dao.Conn()
if err != nil {
return
}
}
func TestUser_GetUser(t *testing.T) {
var user User
// 存在的用户
err := user.GetByName("eigeen")
if err != nil {
t.Error(err)
}
t.Log(user)
// 不存在的用户
err = user.GetByName("unknown_user")
if err != sql.ErrNoRows {
t.Error(err)
}
}

View File

@ -3,6 +3,7 @@ package common
import ( import (
"drive-linked/config" "drive-linked/config"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
"strings"
"time" "time"
) )
@ -12,8 +13,16 @@ type JwtClaims struct {
} }
//TODO:token解密验证 //TODO:token解密验证
func VerifyToken(authorization string) error { func ValidateLogin(authorization string) error {
token, err := jwt.Parse(authorization, func(token *jwt.Token) (interface{}, error) { // 取出Bearer后的内容
var tokenString string
if auths := strings.Split(authorization, " "); len(auths) > 1 {
tokenString = auths[1]
} else {
return jwt.ErrInvalidKey
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Cfg.Security.Jwt.Secret), nil return []byte(config.Cfg.Security.Jwt.Secret), nil
}) })
@ -23,7 +32,7 @@ func VerifyToken(authorization string) error {
return err return err
} }
func NewToken(expire time.Duration, auds ...string) (string, error) { func NewToken(auds ...string) (string, error) {
if len(auds) == 0 { if len(auds) == 0 {
auds = []string{"non-audience"} auds = []string{"non-audience"}
} }
@ -32,7 +41,7 @@ func NewToken(expire time.Duration, auds ...string) (string, error) {
"bar", "bar",
jwt.RegisteredClaims{ jwt.RegisteredClaims{
// A usual scenario is to set the expiration time relative to the current time // A usual scenario is to set the expiration time relative to the current time
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expire)), ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(config.Cfg.Security.Jwt.Expire) * time.Second)),
IssuedAt: jwt.NewNumericDate(time.Now()), IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()), NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: "drivelinked", Issuer: "drivelinked",
@ -48,11 +57,3 @@ func NewToken(expire time.Duration, auds ...string) (string, error) {
} }
return ss, nil return ss, nil
} }
func NewShortToken(auds ...string) (string, error) {
return NewToken(time.Duration(config.Cfg.Security.Jwt.Expire) * time.Second)
}
func NewRefreshToken(auds ...string) (string, error) {
return NewToken(24 * time.Hour)
}

View File

@ -19,7 +19,7 @@ func TestValidateLogin(t *testing.T) {
config.SetupConfig() config.SetupConfig()
tokenString, _ := NewToken("eigeen") tokenString, _ := NewToken("eigeen")
err := VerifyToken(tokenString) err := ValidateLogin(tokenString)
if err == nil { if err == nil {
t.Log("验证通过") t.Log("验证通过")
} else { } else {

View File

@ -0,0 +1,38 @@
package controller
import (
"drive-linked/pkg/dto"
"drive-linked/pkg/service"
"encoding/json"
"github.com/kataras/iris/v12"
"io/ioutil"
"net/http"
)
func UserProfile(ctx iris.Context) {
serv := service.NewUsersService(ctx)
switch ctx.Request().Method {
// GET
case http.MethodGet:
serv.GetOneUser(ctx.Params().GetString("name"), service.MethodUserName)
return
// POST
case http.MethodPost:
//TODO:错误处理
body, err := ioutil.ReadAll(ctx.Request().Body)
if err != nil {
return
}
var req dto.QueryUserParams
err = json.Unmarshal(body, &req)
if err != nil {
return
}
serv.GetOneUser(req.Value, req.Method)
return
}
}

View File

@ -1,37 +0,0 @@
package dao
import (
"fmt"
"strings"
)
type Conditions *map[string]interface{}
//TODO:未完成的sql语句构建器
type QuerySql struct {
Table string
Tail string
Conditions Conditions
Rebind int
body string
}
func (b *QuerySql) Build() {
if b.Conditions == nil {
}
var where []string
var values []interface{}
for k, v := range *b.Conditions {
values = append(values, v)
where = append(where, fmt.Sprintf(`"%s"=%s`, k, "?"))
}
b.body = "SELECT * FROM " + b.Table + " WHERE " + strings.Join(where, "AND")
}
func (b *QuerySql) String() {
}

View File

@ -2,7 +2,6 @@ package dto
import ( import (
"drive-linked/pkg/serializer" "drive-linked/pkg/serializer"
"github.com/kataras/golog"
"github.com/kataras/iris/v12" "github.com/kataras/iris/v12"
"net/http" "net/http"
) )
@ -11,18 +10,21 @@ type Response struct {
Ctx iris.Context Ctx iris.Context
} }
const errJsonUnmarshalMsg = "{\"code\":500,\"msg\":\"Json解析错误请联系管理员\",\"data\":null}"
func NewResponse(ctx iris.Context) *Response { func NewResponse(ctx iris.Context) *Response {
return &Response{Ctx: ctx} return &Response{Ctx: ctx}
} }
const errJsonUnmarshalMsg = "{\"code\":500,\"msg\":\"Json解析错误请联系管理员\",\"data\":null}"
// 成功 统一处理 // 成功 统一处理
func (r *Response) Success(data interface{}) { func (r *Response) Success(data interface{}) {
resp := serializer.ResponseSerial{Code: http.StatusOK, Data: data} res := serializer.Response{
_, err := r.Ctx.JSON(resp) Code: 200,
Msg: "",
Data: data,
}
_, err := r.Ctx.JSON(res)
if err != nil { if err != nil {
golog.Error("Json解析错误: ", resp)
r.Ctx.Write([]byte(errJsonUnmarshalMsg)) r.Ctx.Write([]byte(errJsonUnmarshalMsg))
return return
} }
@ -30,8 +32,12 @@ func (r *Response) Success(data interface{}) {
// 失败 统一处理 // 失败 统一处理
func (r *Response) Error(code int, msg string) { func (r *Response) Error(code int, msg string) {
resp := serializer.ResponseSerial{Code: code, Msg: msg} res := serializer.Response{
_, err := r.Ctx.JSON(resp) Code: code,
Msg: msg,
Data: nil,
}
_, err := r.Ctx.JSON(res)
if err != nil { if err != nil {
r.Ctx.Write([]byte(errJsonUnmarshalMsg)) r.Ctx.Write([]byte(errJsonUnmarshalMsg))
return return
@ -47,8 +53,3 @@ func (r *Response) ErrBadRequest() {
func (r *Response) ErrUnauthorized() { func (r *Response) ErrUnauthorized() {
r.Error(http.StatusUnauthorized, "未登录") r.Error(http.StatusUnauthorized, "未登录")
} }
// 账号或密码错误
func (r *Response) ErrBadAccPasswd() {
r.Error(serializer.ErrBadLogin, "账号或密码错误")
}

View File

@ -1,7 +1,7 @@
package dto package dto
import ( import (
"drive-linked/pkg/model" "drive-linked/model"
"github.com/jinzhu/copier" "github.com/jinzhu/copier"
) )
@ -15,6 +15,11 @@ type UserProfile struct {
Roles string `json:"roles"` Roles string `json:"roles"`
} }
type QueryUserParams struct {
Method string `json:"method"`
Value string `json:"value"`
}
func (u *UserProfile) CopyOf(user *model.User) error { func (u *UserProfile) CopyOf(user *model.User) error {
err := copier.Copy(u, user) err := copier.Copy(u, user)
if err != nil { if err != nil {
@ -22,13 +27,3 @@ func (u *UserProfile) CopyOf(user *model.User) error {
} }
return nil return nil
} }
type QueryUserParams struct {
Method string `json:"method"`
Value string `json:"value"`
}
type LoginParams struct {
Account string `json:"account"`
Password string `json:"password"`
}

View File

@ -4,23 +4,14 @@ import (
"drive-linked/pkg/common" "drive-linked/pkg/common"
"drive-linked/pkg/dto" "drive-linked/pkg/dto"
"github.com/kataras/iris/v12" "github.com/kataras/iris/v12"
"strings"
) )
func SignRequired(ctx iris.Context) { func SignRequired(ctx iris.Context) {
auth := ctx.GetHeader("Authorization") auth := ctx.GetHeader("Authorization")
//TODO:更详细的判断,包括请求格式是否正确 //TODO:更详细的判断,包括请求格式是否正确
// 取出Bearer后的内容
var tokenString string
if auths := strings.Split(auth, " "); len(auths) > 1 {
tokenString = auths[1]
} else {
ctx.Skip()
}
// 验证token // 验证token
err := common.VerifyToken(tokenString) err := common.ValidateLogin(auth)
if err == nil { if err == nil {
ctx.Values().Set("logged_in", true) ctx.Values().Set("logged_in", true)
ctx.Next() ctx.Next()

View File

@ -1,27 +0,0 @@
package model
import (
"drive-linked/pkg/dao"
"fmt"
)
const (
LoginMethodName = "name"
LoginMethodEmail = "email"
)
type Login struct {
ID int64
Name string
Password string
}
func (u *Login) GetLoginInfo(account, method string) error {
exec := fmt.Sprintf(`SELECT id, name, password FROM users WHERE %s=?`, method)
err := dao.DB.Get(u, exec, account)
if err != nil {
return err
}
return nil
}

View File

@ -1,39 +0,0 @@
package model
import (
"drive-linked/pkg/dao"
"fmt"
"github.com/jmoiron/sqlx"
"strings"
)
type User struct {
ID int64 `json:"id,string"`
Name string `json:"name"`
Nickname string `json:"nickname"`
Email string `json:"email"`
Password string `json:"-"`
Status int32 `json:"status"`
Avatar string `json:"avatar"`
Roles string `json:"roles"`
}
func (user *User) GetProfileWithConditions(conditions *map[string]interface{}) error {
// 支持多条件查询
//TODO:分离多条件查询部分,有利于代码复用
var where []string
var values []interface{}
for k, v := range *conditions {
values = append(values, v)
where = append(where, fmt.Sprintf(`"%s" = %s`, k, "?"))
}
exec := sqlx.Rebind(sqlx.QUESTION, "SELECT * FROM users WHERE "+strings.Join(where, "AND")+" LIMIT 1")
err := dao.DB.Get(user, exec, values...)
if err != nil {
return err
}
return nil
}

View File

@ -1,22 +0,0 @@
package model
import (
"drive-linked/pkg/dao"
"testing"
)
func TestUser_GetWithConditions(t *testing.T) {
dao.Conn()
var user User
// 存在的用户
conditions := &map[string]interface{}{
"name": "eigeen",
"email": "375109735@qq.com",
}
err := user.GetProfileWithConditions(conditions)
if err != nil {
t.Error(err)
}
t.Log(user)
}

View File

@ -1,6 +0,0 @@
package serializer
type LoginResponse struct {
Token string `json:"token"`
RefreshToken string `json:"refresh_token"`
}

View File

@ -1,6 +1,8 @@
package serializer package serializer
type ResponseSerial struct { import "net/http"
type Response struct {
Code int `json:"code"` Code int `json:"code"`
Msg string `json:"msg"` Msg string `json:"msg"`
Data interface{} `json:"data"` Data interface{} `json:"data"`
@ -8,10 +10,17 @@ type ResponseSerial struct {
/* /*
自定义错误码 自定义错误码
40000 业务逻辑错误 10000 用户操作
50000 服务器操作
*/ */
const ( const (
ErrNoUser = 40001 ErrNoUser = 10001
ErrBadLogin = 40002
) )
func Success(data interface{}) Response {
r := Response{
Code: http.StatusOK,
Msg: "",
Data: data,
}
return r
}

View File

@ -2,34 +2,37 @@ package service
import ( import (
"database/sql" "database/sql"
"drive-linked/pkg/common" "drive-linked/model"
"drive-linked/pkg/dto" "drive-linked/pkg/dto"
"drive-linked/pkg/model"
"drive-linked/pkg/serializer" "drive-linked/pkg/serializer"
"drive-linked/pkg/utils"
"github.com/kataras/iris/v12" "github.com/kataras/iris/v12"
"net/http" "net/http"
"regexp"
) )
type UsersService struct { type UsersService struct {
Ctx iris.Context Ctx iris.Context
} }
var ( const (
UserConditions = [...]string{"id", "name", "email", "nickname"} MethodUserName = "name"
MethodUserEmail = "email"
) )
func NewUsersService(ctx iris.Context) *UsersService { func NewUsersService(ctx iris.Context) *UsersService {
return &UsersService{Ctx: ctx} return &UsersService{Ctx: ctx}
} }
func (serv *UsersService) GetOneUser(conditions *map[string]interface{}) { func (serv *UsersService) GetOneUser(field, method string) {
var err error var err error
resp := dto.NewResponse(serv.Ctx) resp := dto.NewResponse(serv.Ctx)
user := &model.User{} user := &model.User{}
err = user.GetProfileWithConditions(conditions) switch method {
case MethodUserName:
err = user.GetByName(field)
case MethodUserEmail:
err = user.GetByEmail(field)
}
switch err { switch err {
case nil: case nil:
@ -41,46 +44,7 @@ func (serv *UsersService) GetOneUser(conditions *map[string]interface{}) {
} }
resp.Success(userResult) resp.Success(userResult)
case sql.ErrNoRows: case sql.ErrNoRows:
resp.Error(serializer.ErrNoUser, "用户不存在") resp.Error(serializer.ErrNoUser, "找不到此用户")
default:
resp.Error(http.StatusInternalServerError, "获取用户信息失败,数据库异常")
}
}
func (serv *UsersService) Login(loginParams dto.LoginParams) {
var err error
resp := dto.NewResponse(serv.Ctx)
// 登录逻辑
// 判断账号类型 邮箱/用户名
var method string
emailExp := regexp.MustCompile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
if emailExp.Match([]byte(loginParams.Account)) {
method = model.LoginMethodEmail
} else {
method = model.LoginMethodName
}
// 从数据库取出原密码
userLogin := model.Login{}
err = userLogin.GetLoginInfo(loginParams.Account, method)
switch err {
case nil:
// 检查密码
match, _ := utils.CheckPasswd(loginParams.Password, userLogin.Password)
if match {
// 登录成功签发token
sToken, _ := common.NewShortToken(userLogin.Name)
rToken, _ := common.NewRefreshToken(userLogin.Name)
resp.Success(serializer.LoginResponse{
Token: sToken,
RefreshToken: rToken,
})
} else {
resp.ErrBadAccPasswd()
}
case sql.ErrNoRows:
resp.Error(serializer.ErrNoUser, "用户不存在")
default: default:
resp.Error(http.StatusInternalServerError, "获取用户信息失败,数据库异常") resp.Error(http.StatusInternalServerError, "获取用户信息失败,数据库异常")
} }

View File

@ -12,8 +12,8 @@ func GenPasswd(originPasswd string) (passwd string, err error) {
return passwd, nil return passwd, nil
} }
func CheckPasswd(password string, hash string) (match bool, err error) { func CheckPasswd(originPasswd string, passwd string) (match bool, err error) {
match, err = argon2id.ComparePasswordAndHash(password, hash) match, err = argon2id.ComparePasswordAndHash(originPasswd, passwd)
if err != nil { if err != nil {
return false, err return false, err
} }

View File

@ -1,43 +0,0 @@
package controller
import (
"drive-linked/pkg/dto"
"drive-linked/pkg/service"
"encoding/json"
"github.com/kataras/iris/v12"
)
func UserProfile(ctx iris.Context) {
serv := service.NewUsersService(ctx)
resp := dto.NewResponse(ctx)
// 获取所有查询条件参数
conditions := make(map[string]interface{})
for _, field := range service.UserConditions {
if ctx.URLParam(field) != "" {
conditions[field] = ctx.URLParam(field)
}
}
if len(conditions) == 0 {
resp.ErrBadRequest()
return
}
serv.GetOneUser(&conditions)
}
func UserLogin(ctx iris.Context) {
serv := service.NewUsersService(ctx)
resp := dto.NewResponse(ctx)
var loginParams dto.LoginParams
// 转换参数
body, _ := ctx.GetBody()
err := json.Unmarshal(body, &loginParams)
if err != nil {
resp.ErrBadRequest()
}
serv.Login(loginParams)
}

View File

@ -1,10 +1,9 @@
package router package router
import ( import (
"drive-linked/pkg/controller"
"drive-linked/pkg/middleware" "drive-linked/pkg/middleware"
"drive-linked/router/controller"
"github.com/kataras/iris/v12" "github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/core/router"
) )
func Router() *iris.Application { func Router() *iris.Application {
@ -17,14 +16,12 @@ func Router() *iris.Application {
// 注册路由 // 注册路由
// v1 // v1
v1 := app.Party("/v1") v1 := app.Party("/v1")
v1.PartyFunc("/auth", func(auth router.Party) {
auth.Post("/login", controller.UserLogin)
})
v1.PartyFunc("/users", func(users iris.Party) { v1.PartyFunc("/users", func(users iris.Party) {
// 需要登录 // 需要登录
users.Use(middleware.SignRequired) users.Use(middleware.SignRequired)
// 用户详细信息 // 用户详细信息
users.Get("/profile", controller.UserProfile) users.Get("/profile/{name:string}", controller.UserProfile)
users.Post("/profile", controller.UserProfile)
}) })
return app return app
} }