Compare commits

..

2 Commits

Author SHA1 Message Date
Eigeen 35801f5ee9 Feat: 登录接口实现
continuous-integration/drone/push Build is passing Details
2022-04-09 11:48:44 +08:00
Eigeen 0df2aaa82f 大面积重构
Response部分

usersController部分

中间件部分
2022-04-06 13:54:48 +08:00
19 changed files with 285 additions and 169 deletions

View File

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

View File

@ -1,32 +0,0 @@
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
}

View File

@ -1,30 +0,0 @@
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,7 +3,6 @@ package common
import (
"drive-linked/config"
"github.com/golang-jwt/jwt/v4"
"strings"
"time"
)
@ -13,16 +12,8 @@ type JwtClaims struct {
}
//TODO:token解密验证
func ValidateLogin(authorization string) 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) {
func VerifyToken(authorization string) error {
token, err := jwt.Parse(authorization, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Cfg.Security.Jwt.Secret), nil
})
@ -32,7 +23,7 @@ func ValidateLogin(authorization string) error {
return err
}
func NewToken(auds ...string) (string, error) {
func NewToken(expire time.Duration, auds ...string) (string, error) {
if len(auds) == 0 {
auds = []string{"non-audience"}
}
@ -41,7 +32,7 @@ func NewToken(auds ...string) (string, error) {
"bar",
jwt.RegisteredClaims{
// A usual scenario is to set the expiration time relative to the current time
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(config.Cfg.Security.Jwt.Expire) * time.Second)),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expire)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: "drivelinked",
@ -57,3 +48,11 @@ func NewToken(auds ...string) (string, error) {
}
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()
tokenString, _ := NewToken("eigeen")
err := ValidateLogin(tokenString)
err := VerifyToken(tokenString)
if err == nil {
t.Log("验证通过")
} else {

View File

@ -1,38 +0,0 @@
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
}
}

37
pkg/dao/sentences.go Normal file
View File

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

View File

@ -1,7 +1,7 @@
package dto
import (
"drive-linked/model"
"drive-linked/pkg/model"
"github.com/jinzhu/copier"
)
@ -15,11 +15,6 @@ type UserProfile struct {
Roles string `json:"roles"`
}
type QueryUserParams struct {
Method string `json:"method"`
Value string `json:"value"`
}
func (u *UserProfile) CopyOf(user *model.User) error {
err := copier.Copy(u, user)
if err != nil {
@ -27,3 +22,13 @@ func (u *UserProfile) CopyOf(user *model.User) error {
}
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,14 +4,23 @@ import (
"drive-linked/pkg/common"
"drive-linked/pkg/dto"
"github.com/kataras/iris/v12"
"strings"
)
func SignRequired(ctx iris.Context) {
auth := ctx.GetHeader("Authorization")
//TODO:更详细的判断,包括请求格式是否正确
// 取出Bearer后的内容
var tokenString string
if auths := strings.Split(auth, " "); len(auths) > 1 {
tokenString = auths[1]
} else {
ctx.Skip()
}
// 验证token
err := common.ValidateLogin(auth)
err := common.VerifyToken(tokenString)
if err == nil {
ctx.Values().Set("logged_in", true)
ctx.Next()

27
pkg/model/login.go Normal file
View File

@ -0,0 +1,27 @@
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
}

39
pkg/model/user.go Normal file
View File

@ -0,0 +1,39 @@
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
}

22
pkg/model/user_test.go Normal file
View File

@ -0,0 +1,22 @@
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)
}

6
pkg/serializer/login.go Normal file
View File

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

View File

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

View File

@ -2,37 +2,34 @@ package service
import (
"database/sql"
"drive-linked/model"
"drive-linked/pkg/common"
"drive-linked/pkg/dto"
"drive-linked/pkg/model"
"drive-linked/pkg/serializer"
"drive-linked/pkg/utils"
"github.com/kataras/iris/v12"
"net/http"
"regexp"
)
type UsersService struct {
Ctx iris.Context
}
const (
MethodUserName = "name"
MethodUserEmail = "email"
var (
UserConditions = [...]string{"id", "name", "email", "nickname"}
)
func NewUsersService(ctx iris.Context) *UsersService {
return &UsersService{Ctx: ctx}
}
func (serv *UsersService) GetOneUser(field, method string) {
func (serv *UsersService) GetOneUser(conditions *map[string]interface{}) {
var err error
resp := dto.NewResponse(serv.Ctx)
user := &model.User{}
switch method {
case MethodUserName:
err = user.GetByName(field)
case MethodUserEmail:
err = user.GetByEmail(field)
}
err = user.GetProfileWithConditions(conditions)
switch err {
case nil:
@ -44,7 +41,46 @@ func (serv *UsersService) GetOneUser(field, method string) {
}
resp.Success(userResult)
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:
resp.Error(http.StatusInternalServerError, "获取用户信息失败,数据库异常")
}

View File

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

View File

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