框架基本搭建完成

This commit is contained in:
2022-04-03 12:30:50 +08:00
commit ec4c957b25
31 changed files with 1353 additions and 0 deletions

106
pkg/common/token.go Normal file
View File

@@ -0,0 +1,106 @@
package common
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"drive-linked/config"
"drive-linked/pkg/utils"
"github.com/golang-jwt/jwt/v4"
"github.com/kataras/golog"
"io/ioutil"
"os"
"time"
)
type JwtClaims struct {
Foo string `json:"foo"`
jwt.RegisteredClaims
}
var ECDSAKey *ecdsa.PrivateKey
// 生成ES256密钥对并保存在文件中
func init() {
// 密钥对存在时跳过
//TODO:bug:会重复生成key
if isExist := utils.FileExist("id_ecdsa") && utils.FileExist("id_ecdsa.pub"); isExist {
return
}
key, err := newES256Key()
if err != nil {
golog.Fatal("生成ES256密钥错误")
}
// 写入至文件
pubKeyBytes, err := utils.EncodePublicKey(&key.PublicKey)
if err != nil {
golog.Fatal(err)
}
priKeyBytes, err := utils.EncodePrivateKey(key)
if err != nil {
golog.Fatal(err)
}
priKeyFile, err := os.OpenFile("id_ecdsa", os.O_CREATE, 0600)
if err != nil {
golog.Fatal(err)
}
pubKeyFile, err := os.OpenFile("id_ecdsa.pub", os.O_CREATE, 0655)
if err != nil {
golog.Fatal(err)
}
priKeyFile.Write(priKeyBytes)
pubKeyFile.Write(pubKeyBytes)
}
func newES256Key() (key *ecdsa.PrivateKey, err error) {
key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
return key, err
}
func LoadKey() error {
if ECDSAKey != nil {
return nil
}
priKeyBytes, err := ioutil.ReadFile(config.Cfg.Security.Jwt.PrivateKey)
if err != nil {
return err
}
key, err := utils.DecodePrivateKey(priKeyBytes)
if err != nil {
return err
}
ECDSAKey = key
return nil
}
//TODO:token解密验证
func ValidateLogin(token string) error {
return nil
}
func NewToken(auds ...string) (string, error) {
// Create the claims
claims := JwtClaims{
"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)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: "drivelinked",
Subject: "login",
Audience: []string{"eigeen"},
},
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
ss, err := token.SignedString(ECDSAKey)
if err != nil {
return "", err
}
return ss, nil
}

20
pkg/common/token_test.go Normal file
View File

@@ -0,0 +1,20 @@
package common
import (
"drive-linked/config"
"testing"
)
func TestNewToken(t *testing.T) {
config.SetupConfig()
err := LoadKey()
if err != nil {
t.Fatal(err)
}
token, err := NewToken("eigeen")
if err != nil {
t.Error(err)
}
t.Log(token)
}

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.QueryUser
err = json.Unmarshal(body, &req)
if err != nil {
return
}
serv.GetOneUser(req.Value, req.Method)
return
}
}

43
pkg/dao/sqlx.go Normal file
View File

@@ -0,0 +1,43 @@
package dao
import (
"drive-linked/assets"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"io/ioutil"
"time"
)
var DB *sqlx.DB
// 初始化数据库连接
func Conn() (err error) {
dsn := "file:drivelinked.db?cache=shared&mode=rwc"
DB, err = sqlx.Connect("sqlite3", dsn)
if err != nil {
return err
}
// 基本配置
DB.SetMaxIdleConns(20)
DB.SetMaxOpenConns(50)
DB.SetConnMaxLifetime(time.Second * 30)
return nil
}
// 初始化表
func InitTables() error {
sqlf, err := assets.SqlStat.Open("sql/mysql.sql")
defer sqlf.Close()
if err != nil {
return err
}
exec, err := ioutil.ReadAll(sqlf)
if err != nil {
return err
}
DB.MustExec(string(exec))
return nil
}

19
pkg/dao/sqlx_test.go Normal file
View File

@@ -0,0 +1,19 @@
package dao
import "testing"
func TestInitDB(t *testing.T) {
err := Conn()
if err != nil {
t.Error(err)
return
}
}
func TestInitTables(t *testing.T) {
Conn()
err := InitTables()
if err != nil {
t.Error(err)
}
}

59
pkg/dto/response.go Normal file
View File

@@ -0,0 +1,59 @@
package dto
import (
"drive-linked/pkg/serializer"
"github.com/kataras/iris/v12"
"net/http"
)
type Response struct {
Ctx iris.Context
}
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)
if err != nil {
r.Ctx.Write([]byte(errJsonUnmarshalMsg))
return
}
}
// 失败 统一处理
func (r *Response) Error(code int32, msg string) {
res := serializer.Response{
Code: code,
Msg: msg,
Data: nil,
}
_, err := r.Ctx.JSON(res)
if err != nil {
r.Ctx.Write([]byte(errJsonUnmarshalMsg))
return
}
}
// 参数类型错误
func (r *Response) ErrInvalidParamType() (err error) {
res := serializer.Response{
Code: http.StatusBadRequest,
Msg: "参数类型错误",
Data: nil,
}
_, err = r.Ctx.JSON(res)
if err != nil {
return err
}
return nil
}

29
pkg/dto/user.go Normal file
View File

@@ -0,0 +1,29 @@
package dto
import (
"drive-linked/pkg/model"
"github.com/jinzhu/copier"
)
type UserProfile struct {
Id int64 `json:"id,string"`
Name string `json:"name"`
Nickname string `json:"nickname"`
Email string `json:"email"`
Status int32 `json:"status"`
Avatar string `json:"avatar"`
Roles string `json:"roles"`
}
type QueryUser 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 {
return err
}
return nil
}

18
pkg/global/global.go Normal file
View File

@@ -0,0 +1,18 @@
package global
import "fmt"
type Version struct {
Major int32
Minor int32
Patch int32
Tag string
}
func (v *Version) String() string {
vs := fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
if v.Tag == "" {
vs = vs + "-" + v.Tag
}
return vs
}

16
pkg/middleware/auth.go Normal file
View File

@@ -0,0 +1,16 @@
package middleware
import (
"drive-linked/pkg/common"
"github.com/kataras/iris/v12"
)
func SignRequired(ctx iris.Context) {
auth := ctx.GetHeader("Authorization")
//TODO:更详细的判断,包括请求格式是否正确
err := common.ValidateLogin(auth)
if err == nil {
ctx.Values().Set("logged_in", true)
}
ctx.Next()
}

8
pkg/middleware/global.go Normal file
View File

@@ -0,0 +1,8 @@
package middleware
import "github.com/kataras/iris/v12"
func AllowAllCORS(ctx iris.Context) {
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Next()
}

32
pkg/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
pkg/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

@@ -0,0 +1,26 @@
package serializer
import "net/http"
type Response struct {
Code int32 `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
/*
自定义错误码
10000 用户操作
*/
const (
ErrNoUser = 10001
)
func Success(data interface{}) Response {
r := Response{
Code: http.StatusOK,
Msg: "",
Data: data,
}
return r
}

51
pkg/service/users.go Normal file
View File

@@ -0,0 +1,51 @@
package service
import (
"database/sql"
"drive-linked/pkg/dto"
"drive-linked/pkg/model"
"drive-linked/pkg/serializer"
"github.com/kataras/iris/v12"
"net/http"
)
type UsersService struct {
Ctx iris.Context
}
const (
MethodUserName = "name"
MethodUserEmail = "email"
)
func NewUsersService(ctx iris.Context) *UsersService {
return &UsersService{Ctx: ctx}
}
func (serv *UsersService) GetOneUser(field, method string) {
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)
}
switch err {
case nil:
// 复制到dto对象
var userResult dto.UserProfile
err = userResult.CopyOf(user)
if err != nil {
resp.Error(http.StatusInternalServerError, "service.users Error")
}
resp.Success(userResult)
case sql.ErrNoRows:
resp.Error(serializer.ErrNoUser, "找不到此用户")
default:
resp.Error(http.StatusInternalServerError, "获取用户信息失败,数据库异常")
}
}

8
pkg/utils/file.go Normal file
View File

@@ -0,0 +1,8 @@
package utils
import "os"
func FileExist(path string) bool {
_, err := os.Lstat(path)
return os.IsExist(err)
}

84
pkg/utils/key.go Normal file
View File

@@ -0,0 +1,84 @@
package utils
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
)
func DecodePublicKey(encodedKey []byte) (*ecdsa.PublicKey, error) {
block, _ := pem.Decode(encodedKey)
if block == nil || block.Type != "PUBLIC KEY" {
return nil, fmt.Errorf("marshal: could not decode PEM block type %s", block.Type)
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
ecdsaPub, ok := pub.(*ecdsa.PublicKey)
if !ok {
return nil, errors.New("marshal: data was not an ECDSA public key")
}
return ecdsaPub, nil
}
func EncodePublicKey(key *ecdsa.PublicKey) ([]byte, error) {
derBytes, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return nil, err
}
block := &pem.Block{
Type: "PUBLIC KEY",
Bytes: derBytes,
}
return pem.EncodeToMemory(block), nil
}
func DecodePrivateKey(encodedKey []byte) (*ecdsa.PrivateKey, error) {
var skippedTypes []string
var block *pem.Block
for {
block, encodedKey = pem.Decode(encodedKey)
if block == nil {
return nil, fmt.Errorf("failed to find EC PRIVATE KEY in PEM data after skipping types %v", skippedTypes)
}
if block.Type == "EC PRIVATE KEY" {
break
} else {
skippedTypes = append(skippedTypes, block.Type)
continue
}
}
privKey, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return privKey, nil
}
func EncodePrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
derKey, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, err
}
keyBlock := &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: derKey,
}
return pem.EncodeToMemory(keyBlock), nil
}

32
pkg/utils/key_test.go Normal file
View File

@@ -0,0 +1,32 @@
package utils
import (
"io/ioutil"
"testing"
)
func TestDecodePrivateKey(t *testing.T) {
priKeyStr, err := ioutil.ReadFile("../../config/id_ecdsa")
if err != nil {
t.Fatal(err)
}
key, err := DecodePrivateKey(priKeyStr)
if err != nil {
t.Error(err)
}
t.Log(key)
}
func TestDecodePublicKey(t *testing.T) {
priKeyStr, err := ioutil.ReadFile("../../config/id_ecdsa.pub")
if err != nil {
t.Fatal(err)
}
key, err := DecodePublicKey(priKeyStr)
if err != nil {
t.Error(err)
}
t.Log(key)
}

21
pkg/utils/password.go Normal file
View File

@@ -0,0 +1,21 @@
package utils
import (
"github.com/alexedwards/argon2id"
)
func GenPasswd(originPasswd string) (passwd string, err error) {
passwd, err = argon2id.CreateHash(originPasswd, argon2id.DefaultParams)
if err != nil {
return "", err
}
return passwd, nil
}
func CheckPasswd(originPasswd string, passwd string) (match bool, err error) {
match, err = argon2id.ComparePasswordAndHash(originPasswd, passwd)
if err != nil {
return false, err
}
return match, nil
}

View File

@@ -0,0 +1,41 @@
package utils
import (
"testing"
)
//hashed := fmt.Sprintf("%x", sha256.Sum256([]byte("pa$$word"+"drivelinked")))
var hashed = "2bd6e406749d3fb8ff5c164ee63c4fdc744164f7327ea3ad6abef90df4e64d03"
func TestGenPasswd(t *testing.T) {
passwd, err := GenPasswd(hashed)
if err != nil {
t.Error(err)
}
t.Log(passwd)
}
func TestCheckPasswd(t *testing.T) {
passwd, err := GenPasswd(hashed)
if err != nil {
t.Error(err)
}
// 匹配
match, err := CheckPasswd(hashed, passwd)
if err != nil {
t.Error(err)
}
if !match {
t.Fail()
}
// 不匹配
match, err = CheckPasswd("abc", passwd)
if err != nil {
t.Error(err)
}
if match {
t.Fail()
}
}

25
pkg/utils/snowflake.go Normal file
View File

@@ -0,0 +1,25 @@
package utils
import "github.com/bwmarrin/snowflake"
var SfNode *snowflake.Node
func init() {
var (
err error
)
// 初始化
SfNode, err = snowflake.NewNode(1)
if err != nil {
return
}
}
func Snowflake() snowflake.ID {
return SfNode.Generate()
}
func SnowflakeInt64() int64 {
return Snowflake().Int64()
}

View File

@@ -0,0 +1,13 @@
package utils
import "testing"
func TestSnowflake(t *testing.T) {
id := Snowflake()
t.Log(id.String())
}
func TestSnowflakeInt64(t *testing.T) {
id := SnowflakeInt64()
t.Log(id)
}