Browse Source

添加:登录注册,用户信息,好友添加

ignatz 3 years ago
commit
81ca30df9f
12 changed files with 863 additions and 0 deletions
  1. 15 0
      .vscode/launch.json
  2. 11 0
      apps.go
  3. 51 0
      basic/method.go
  4. 82 0
      friend/handler.go
  5. 146 0
      friend/model.go
  6. 34 0
      go.mod
  7. 114 0
      go.sum
  8. 21 0
      main.go
  9. 30 0
      message/model.go
  10. 186 0
      user/handler.go
  11. 112 0
      user/method.go
  12. 61 0
      user/model.go

+ 15 - 0
.vscode/launch.json

@@ -0,0 +1,15 @@
+{
+    // 使用 IntelliSense 了解相关属性。 
+    // 悬停以查看现有属性的描述。
+    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
+    "version": "0.2.0",
+    "configurations": [
+        {
+            "name": "Launch Package",
+            "type": "go",
+            "request": "launch",
+            "mode": "auto",
+            "program": "${fileDirname}"
+        }
+    ]
+}

+ 11 - 0
apps.go

@@ -0,0 +1,11 @@
+package main
+
+import (
+	"prime/friend"
+	"prime/user"
+)
+
+func migrate() {
+	user.Migrate()
+	friend.Migrate()
+}

+ 51 - 0
basic/method.go

@@ -0,0 +1,51 @@
+package basic
+
+import (
+	"errors"
+	"net/http"
+
+	"github.com/gin-gonic/gin"
+	"gorm.io/driver/sqlite"
+	"gorm.io/gorm"
+)
+
+var FileDirPath = "/home/ubuntu/prime_server/files/"
+
+var db *gorm.DB
+
+func DB() *gorm.DB {
+	return db
+}
+
+var r *gin.Engine
+
+func R() *gin.Engine {
+	return r
+}
+
+var ErrFriendExist = errors.New("Friend already exists.")
+var ErrForbidden = errors.New("Forbidden.")
+var ErrApplicationAlreadyReplied = errors.New("Already replied.")
+
+func ErrCode(err error) (code int) {
+	switch err {
+	case ErrForbidden, ErrApplicationAlreadyReplied:
+		code = http.StatusForbidden
+	case gorm.ErrRecordNotFound:
+		code = http.StatusNotFound
+	case ErrFriendExist:
+		code = http.StatusConflict
+	default:
+		code = http.StatusInternalServerError
+	}
+	return code
+}
+
+func init() {
+	_db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
+	if err != nil {
+		panic("failed to connect database")
+	}
+	db = _db
+	r = gin.Default()
+}

+ 82 - 0
friend/handler.go

@@ -0,0 +1,82 @@
+package friend
+
+import (
+	"fmt"
+	"net/http"
+
+	"prime/user"
+
+	. "prime/basic"
+
+	"github.com/gin-gonic/gin"
+)
+
+func init() {
+	r := user.Authorized
+	r.GET("applications", getApplicationsHandler)
+	r.POST("application", postApplicationHandler)
+	r.PATCH("application", patchApplicationHandler)
+	r.GET("friends", getFriendsHandler)
+}
+
+func getFriendsHandler(c *gin.Context) {
+	uid := c.MustGet("uid").(uint)
+	friends, err := GetFriends(uid)
+	fmt.Println(friends)
+	if err == nil {
+		c.JSON(http.StatusOK, gin.H{"friends": friends})
+	} else {
+		c.JSON(ErrCode(err), gin.H{"error": err.Error()})
+	}
+}
+
+func getApplicationsHandler(c *gin.Context) {
+	uid := c.MustGet("uid").(uint)
+	apps, err := GetApplications(uid)
+	if err == nil {
+		c.JSON(http.StatusOK, gin.H{"apps": apps})
+	} else {
+		c.JSON(ErrCode(err), gin.H{"error": err.Error()})
+	}
+}
+
+func postApplicationHandler(c *gin.Context) {
+	uid := c.MustGet("uid").(uint)
+	var form struct {
+		Receiver uint   `json:"receiver" binding:"required"`
+		Message  []byte `json:"message" binding:"required"`
+	}
+	if err := c.Bind(&form); err == nil {
+		appID, err := ApplyFriend(uid, form.Receiver, form.Message)
+		if err == nil {
+			c.JSON(http.StatusOK, gin.H{"appid": appID})
+		} else {
+			c.JSON(ErrCode(err), gin.H{"error": err.Error()})
+		}
+	} else {
+		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+	}
+}
+
+func patchApplicationHandler(c *gin.Context) {
+	uid := c.MustGet("uid").(uint)
+	fmt.Printf("uid=%d\n", uid)
+	var form struct {
+		AppID uint `json:"appid" binding:"required"`
+		Reply int  `json:"reply" binding:"required"`
+	}
+
+	if err := c.Bind(&form); err == nil {
+		fmt.Printf("%+v\n", form)
+		err := ReplyApplication(uid, form.AppID, form.Reply > 0)
+		if err == nil {
+			c.JSON(http.StatusOK, gin.H{"status": "ok"})
+		} else {
+			c.JSON(ErrCode(err), gin.H{"error": err.Error()})
+		}
+	} else {
+		// TODO: 发送reply为0则无法读取???
+		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+		panic(err)
+	}
+}

+ 146 - 0
friend/model.go

@@ -0,0 +1,146 @@
+package friend
+
+import (
+	"fmt"
+	. "prime/basic"
+	auth "prime/user"
+
+	"gorm.io/gorm"
+)
+
+type Application struct {
+	gorm.Model
+	SenderID   uint
+	Sender     auth.User
+	ReceiverID uint
+	Receiver   auth.User
+	Status     uint8
+	Message    []byte
+}
+
+func Migrate() {
+	db := DB()
+	db.AutoMigrate(&Application{})
+	// db.Create(&User{Username: "foo", Password: "bar"})
+}
+
+func GetFriends(uid uint) ([]auth.Profile, error) {
+	db := DB()
+	var friends []auth.User
+	var profiles []auth.Profile
+	var user auth.User
+	res := db.Find(&user, uid)
+	if res.RowsAffected == 1 {
+		if err := db.Model(&user).Association("Friends").Find(&friends); err != nil {
+			return nil, err
+		}
+		for _, friend := range friends {
+			var profile auth.Profile
+			res := db.Find(&profile, "user_id = ?", friend.ID)
+			if res.Error != nil {
+				return nil, res.Error
+			}
+
+			profiles = append(profiles, profile)
+		}
+		return profiles, nil
+	}
+	return nil, res.Error
+}
+
+func IsFriend(a uint, b uint) (bool, error) {
+	db := DB()
+	var alice, bob auth.User
+	res := db.Find(&alice, a)
+	if res.RowsAffected == 1 {
+		err := db.Model(&alice).Association("Friends").Find(&bob, b)
+		return bob.ID == b, err
+	}
+	return false, res.Error
+}
+
+func AddFriend(a uint, b uint) error {
+	res, err := IsFriend(a, b)
+	if err != nil {
+		fmt.Printf("isfriend err %s\n", err.Error())
+		return err
+	}
+	if res {
+		return ErrFriendExist
+	}
+	var alice, bob auth.User
+	db := DB()
+	resA := db.Take(&alice, a)
+	resB := db.Take(&bob, b)
+	if resA.RowsAffected == 1 && resB.RowsAffected == 1 {
+		alice.Friends = append(alice.Friends, &bob)
+		bob.Friends = append(bob.Friends, &alice)
+		db.Save(alice)
+		db.Save(bob)
+		return nil
+	}
+	return gorm.ErrRecordNotFound
+}
+
+func ApplyFriend(from uint, to uint, message []byte) (uint, error) {
+	res, err := IsFriend(from, to)
+	if err != nil {
+		return 0, err
+	}
+	if res {
+		return 0, ErrFriendExist
+	}
+	db := DB()
+	var sender, receiver auth.User
+	resA := db.Take(&sender, from)
+	resB := db.Take(&receiver, to)
+	if resA.RowsAffected != 1 || resB.RowsAffected != 1 {
+		return 0, gorm.ErrRecordNotFound
+	}
+	app := Application{
+		Sender: sender, Receiver: receiver, Status: 0, Message: message,
+	}
+	db.Create(&app)
+	// TODO: add a notice ?
+	return app.ID, nil
+}
+
+func ReplyApplication(uid uint, appID uint, accepted bool) error {
+	db := DB()
+	var app Application
+	res := db.Find(&app, appID)
+	fmt.Printf("%+v\n%d\n", app, res.RowsAffected)
+	if res.RowsAffected != 1 {
+		return res.Error
+	}
+	if app.ReceiverID != uid {
+		return ErrForbidden
+	}
+	if app.Status != 0 {
+		return ErrApplicationAlreadyReplied
+	}
+	if accepted {
+		app.Status = 1
+		err := AddFriend(app.SenderID, uid)
+		if err != nil {
+			fmt.Printf("addfriend error %s\n", err.Error())
+			return err
+		}
+	} else {
+		app.Status = 2
+	}
+	res = db.Save(&app)
+	return res.Error
+}
+
+func GetApplications(uid uint) ([]Application, error) {
+	db := DB()
+	var user auth.User
+	res := db.Take(&user, uid)
+	var apps []Application
+	if res.RowsAffected == 1 {
+		db.Find(&apps, "sender_id = ? OR receiver_id = ?", uid, uid)
+		return apps, nil
+	}
+	return apps, res.Error
+}

+ 34 - 0
go.mod

@@ -0,0 +1,34 @@
+module prime
+
+go 1.18
+
+require github.com/gin-gonic/gin v1.8.2
+
+require (
+	github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
+	github.com/gin-contrib/sse v0.1.0 // indirect
+	github.com/go-playground/locales v0.14.0 // indirect
+	github.com/go-playground/universal-translator v0.18.0 // indirect
+	github.com/go-playground/validator/v10 v10.11.1 // indirect
+	github.com/goccy/go-json v0.9.11 // indirect
+	github.com/golang-jwt/jwt/v4 v4.4.3 // indirect
+	github.com/google/uuid v1.3.0 // indirect
+	github.com/jinzhu/inflection v1.0.0 // indirect
+	github.com/jinzhu/now v1.1.5 // indirect
+	github.com/json-iterator/go v1.1.12 // indirect
+	github.com/leodido/go-urn v1.2.1 // indirect
+	github.com/mattn/go-isatty v0.0.16 // indirect
+	github.com/mattn/go-sqlite3 v1.14.16 // indirect
+	github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
+	github.com/modern-go/reflect2 v1.0.2 // indirect
+	github.com/pelletier/go-toml/v2 v2.0.6 // indirect
+	github.com/ugorji/go/codec v1.2.7 // indirect
+	golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect
+	golang.org/x/net v0.4.0 // indirect
+	golang.org/x/sys v0.3.0 // indirect
+	golang.org/x/text v0.5.0 // indirect
+	google.golang.org/protobuf v1.28.1 // indirect
+	gopkg.in/yaml.v2 v2.4.0 // indirect
+	gorm.io/driver/sqlite v1.4.3 // indirect
+	gorm.io/gorm v1.24.2 // indirect
+)

+ 114 - 0
go.sum

@@ -0,0 +1,114 @@
+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+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/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
+github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
+github.com/gin-gonic/gin v1.8.2 h1:UzKToD9/PoFj/V4rvlKqTRKnQYyz8Sc1MJlv4JHPtvY=
+github.com/gin-gonic/gin v1.8.2/go.mod h1:qw5AYuDrzRTnhvusDsrov+fDIxp9Dleuu12h8nfB398=
+github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
+github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
+github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=
+github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs=
+github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho=
+github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
+github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ=
+github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU=
+github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=
+github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
+github.com/golang-jwt/jwt/v4 v4.4.3 h1:Hxl6lhQFj4AnOX6MLrsCb/+7tCj7DxP7VA+2rDIq5AU=
+github.com/golang-jwt/jwt/v4 v4.4.3/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
+github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
+github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
+github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
+github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
+github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
+github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
+github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
+github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
+github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
+github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
+github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
+github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
+github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU=
+github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek=
+github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
+github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
+github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M=
+github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
+github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
+golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 h1:0es+/5331RGQPcXlMfP+WrnIIS6dNnNRe0WB02W0F4M=
+golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
+golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
+golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU=
+golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
+golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM=
+golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
+google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
+google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU=
+gorm.io/driver/sqlite v1.4.3/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
+gorm.io/gorm v1.24.0/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA=
+gorm.io/gorm v1.24.2 h1:9wR6CFD+G8nOusLdvkZelOEhpJVwwHzpQOUM+REd6U0=
+gorm.io/gorm v1.24.2/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA=

+ 21 - 0
main.go

@@ -0,0 +1,21 @@
+package main
+
+import (
+	"os"
+	. "prime/basic"
+)
+
+func runserver() {
+	// Listen and Server in 0.0.0.0:8080
+	r := R()
+	r.Run(":8080")
+
+}
+
+func main() {
+	if len(os.Args) > 0 && os.Args[1] == "migrate" {
+		migrate()
+	} else {
+		runserver()
+	}
+}

+ 30 - 0
message/model.go

@@ -0,0 +1,30 @@
+package auth
+
+import (
+	. "prime/basic"
+	"prime/user"
+
+	"gorm.io/gorm"
+)
+
+type Message struct {
+	gorm.Model
+	SenderID   uint
+	Sender     user.User
+	ReceiverID uint
+	Receiver   user.User
+	Received   bool
+}
+
+func Migrate() {
+	db := DB()
+	db.AutoMigrate(&Message{})
+	// db.Create(&User{Username: "foo", Password: "bar"})
+}
+
+func AddFriend(username string, friend string) {
+
+}
+
+func Test() {
+}

+ 186 - 0
user/handler.go

@@ -0,0 +1,186 @@
+package user
+
+import (
+	"fmt"
+	"net/http"
+	. "prime/basic"
+	"strings"
+
+	"github.com/gin-gonic/gin"
+	"github.com/google/uuid"
+)
+
+type UserForm struct {
+	Username string `json:"username" binding:"required"`
+	Password string `json:"password" binding:"required"`
+}
+
+var Authorized *gin.RouterGroup
+
+func init() {
+	r := R()
+
+	r.POST("/token", func(c *gin.Context) {
+
+		// Parse JSON
+		var json UserForm
+
+		if c.Bind(&json) == nil {
+			fmt.Printf("%+v\n", json)
+			token, err := GenToken(json.Username, json.Password)
+			if err == nil {
+				fmt.Println(token)
+				c.JSON(http.StatusOK, gin.H{"token": token})
+			} else {
+				c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
+			}
+		}
+
+	})
+
+	r.POST("/user", func(c *gin.Context) {
+		var json UserForm
+		if c.Bind(&json) == nil {
+			user, err := Register(json.Username, json.Password)
+			if err == nil {
+				c.JSON(http.StatusOK, gin.H{"uid": user.ID})
+			} else {
+				c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
+			}
+		}
+	})
+
+	Authorized = r.Group("/", JWTAuthMiddleware())
+
+	Authorized.GET("home", homeHandler)
+
+	Authorized.POST("message", func(c *gin.Context) {
+		user := c.MustGet("username").(string)
+
+		fmt.Printf("username=%s\n", user)
+
+		// Parse JSON
+		var json struct {
+			Sender   string `json:"sender" binding:"required"`
+			Receiver string `json:"receiver" binding:"required"`
+			Message  string `json:"message" binding:"required"`
+		}
+
+		if c.Bind(&json) == nil {
+			fmt.Printf("%+v\n", json)
+			c.JSON(http.StatusOK, gin.H{})
+		}
+
+	})
+
+	Authorized.POST("avatar", func(c *gin.Context) {
+		uid := c.MustGet("uid").(uint)
+		fmt.Printf("upload avatar uid=%d\n", uid)
+		file, err := c.FormFile("file")
+		if err != nil {
+			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+			return
+		}
+		filename := file.Filename
+		pos := strings.LastIndex(filename, ".")
+		if pos == -1 {
+			c.JSON(http.StatusBadRequest, gin.H{"error": "filename error"})
+			return
+		}
+		filename = uuid.New().String() + filename[pos:]
+		if err := c.SaveUploadedFile(file, FileDirPath+filename); err != nil {
+			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+			return
+		}
+		fmt.Println(filename)
+		if err := SetAvatar(uid, filename); err != nil {
+			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+			return
+		}
+		c.JSON(http.StatusOK, gin.H{"filename": filename})
+	})
+
+	Authorized.GET("profile/:name", func(c *gin.Context) {
+		name := c.Param("name")
+		// uid, err := strconv.Atoi(c.Param("uid"))
+		// if err != nil {
+		// 	c.JSON(http.StatusBadRequest, gin.H{"status": "bad request", "error": err.Error()})
+		// 	return
+		// }
+		uid, err := GetUID(name)
+		if err != nil {
+			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+			return
+		}
+		if uid == 0 {
+			c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
+			return
+		}
+		profile, err := GetProfile(uid)
+		if err != nil {
+			c.JSON(ErrCode(err), gin.H{"error": err.Error()})
+			return
+		}
+		c.JSON(http.StatusOK, gin.H{"profile": profile})
+	})
+
+	Authorized.GET("file/:filename", func(c *gin.Context) {
+		// uid := c.MustGet("uid").(uint)
+		filename := c.Param("filename")
+		// fmt.Printf("uid(%d) get avatar of id=%d\n", uid, id)
+		// filename, err := GetAvatar(uint(id))
+		c.FileAttachment(FileDirPath+filename, filename)
+	})
+
+}
+
+// JWTAuthMiddleware 基于JWT的认证中间件
+func JWTAuthMiddleware() func(c *gin.Context) {
+	return func(c *gin.Context) {
+		// 客户端携带Token有三种方式 1.放在请求头 2.放在请求体 3.放在URI
+		// 这里假设Token放在Header的Authorization中,并使用Bearer开头
+		// 这里的具体实现方式要依据你的实际业务情况决定
+		authHeader := c.Request.Header.Get("Authorization")
+		// fmt.Println(authHeader)
+		if authHeader == "" {
+			c.JSON(http.StatusBadRequest, gin.H{
+				"error": "请求头中auth为空",
+			})
+			c.Abort()
+			return
+		}
+		// 按空格分割
+		parts := strings.SplitN(authHeader, " ", 2)
+		if !(len(parts) == 2 && parts[0] == "Bearer") {
+			c.JSON(http.StatusBadRequest, gin.H{
+				"error": "请求头中auth格式有误",
+			})
+			c.Abort()
+			return
+		}
+		// parts[1]是获取到的tokenString,我们使用之前定义好的解析JWT的函数来解析它
+		mc, err := ParseToken(parts[1])
+		fmt.Printf("token=%+v\n", mc)
+		if err != nil {
+			c.JSON(http.StatusUnauthorized, gin.H{
+				"error": "无效的Token",
+			})
+			c.Abort()
+			return
+		}
+		// 将当前请求的username信息保存到请求的上下文c上
+		c.Set("username", mc.Username)
+		c.Set("uid", mc.UID)
+		fmt.Printf("username=%s uid=%d\n", mc.Username, mc.UID)
+		c.Next() // 后续的处理函数可以用过c.Get("uid")来获取当前请求的用户信息
+	}
+}
+
+func homeHandler(c *gin.Context) {
+	username := c.MustGet("username").(string)
+	uid := c.MustGet("uid").(uint)
+	c.JSON(http.StatusOK, gin.H{
+		"username": username,
+		"uid":      uid,
+	})
+}

+ 112 - 0
user/method.go

@@ -0,0 +1,112 @@
+package user
+
+import (
+	"errors"
+	"fmt"
+	"time"
+
+	. "prime/basic"
+
+	"github.com/golang-jwt/jwt/v4"
+	"gorm.io/gorm"
+)
+
+type MyClaims struct {
+	Username string `json:"username"`
+	UID      uint   `json:"uid"`
+	jwt.StandardClaims
+}
+
+const TokenExpireDuration = time.Hour * 2
+
+var MySecret = []byte("冬天冬天悄悄过去")
+
+func GenToken(username string, password string) (string, error) {
+	db := DB()
+	var user User
+	result := db.Take(&user, "username = ? AND password = ?", username, password)
+	fmt.Printf("%+v\n", user)
+	if result.RowsAffected == 1 {
+		c := MyClaims{username, user.ID, jwt.StandardClaims{
+			ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(),
+			Issuer:    "my-project",
+		}}
+		token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
+		return token.SignedString(MySecret)
+	}
+	return "", gorm.ErrRecordNotFound
+}
+
+func ParseToken(tokenString string) (*MyClaims, error) {
+	// 解析token
+	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (i interface{}, err error) {
+		return MySecret, nil
+	})
+	if err != nil {
+		return nil, err
+	}
+	if claims, ok := token.Claims.(*MyClaims); ok && token.Valid { // 校验token
+		return claims, nil
+	}
+	return nil, errors.New("invalid token")
+}
+
+func SetAvatar(uid uint, filename string) error {
+	db := DB()
+	var user User
+	user.ID = uid
+	var profile Profile
+	err := db.Model(&user).Association("Profile").Find(&profile)
+	if err != nil {
+		return err
+	}
+	profile.Avatar = filename
+	fmt.Println(profile)
+	res := db.Where("user_id = ?", uid).Save(&profile)
+	// return nil
+	return res.Error
+}
+
+func GetAvatar(uid uint) (string, error) {
+	db := DB()
+	var user User
+	user.ID = uid
+	var profile Profile
+	err := db.Model(&user).Association("Profile").Find(&profile)
+	if err != nil {
+		return "", err
+	}
+	return profile.Avatar, nil
+}
+
+func Register(username string, password string) (user *User, err error) {
+	db := DB()
+	profile := Profile{Name: username, Avatar: "avatar.jpg"}
+	user = &User{Username: username, Password: password, Profile: profile}
+	result := db.Create(user)
+	return user, result.Error
+}
+
+func GetProfile(uid uint) (*Profile, error) {
+	db := DB()
+	var profile Profile
+	res := db.Find(&profile, "user_id = ?", uid)
+	if res.RowsAffected == 1 {
+		return &profile, nil
+	}
+	return nil, res.Error
+}
+
+func GetUID(username string) (uint, error) {
+	db := DB()
+	var user User
+	res := db.Find(&user, "username = ?", username)
+	if res.RowsAffected == 1 {
+		return user.ID, nil
+	}
+	if res.Error == gorm.ErrRecordNotFound {
+		println("user does not exist")
+		return 0, nil
+	}
+	return 0, res.Error
+}

+ 61 - 0
user/model.go

@@ -0,0 +1,61 @@
+package user
+
+import (
+	"fmt"
+	. "prime/basic"
+
+	"gorm.io/gorm"
+)
+
+type User struct {
+	gorm.Model
+	Username string  `gorm:"not null;unique"`
+	Password string  `gorm:"not null"`
+	Friends  []*User `gorm:"many2many:user_friends;"`
+	Profile  Profile `gorm:"not null"`
+}
+
+type Profile struct {
+	// ID     uint `gorm:"primarykey"`
+	UserID uint
+	Name   string
+	Avatar string
+}
+
+func Migrate() {
+	db := DB()
+	db.AutoMigrate(&User{})
+	db.AutoMigrate(&Profile{})
+	// db.Create(&User{Username: "foo", Password: "bar"})
+}
+
+func Test() {
+	db := DB()
+	users := []User{
+		{Username: "foo", Password: "bar"},
+		{Username: "ignatz", Password: "password"},
+		{Username: "alice", Password: "123"},
+		{Username: "bob", Password: "123"},
+	}
+	users[0].Friends = []*User{&users[1], &users[2]}
+	users[1].Friends = []*User{&users[0]}
+	users[2].Friends = []*User{&users[0], &users[3]}
+	users[3].Friends = []*User{&users[2]}
+	// 1-2 1-3 3-4
+	// db.Create(&users)
+	db.Find(&users)
+	// db.Create(&User{Username: "admin", Password: "admin", Friends: []*User{&users[0]}})
+	// printUsers(users)
+	// users[0].Friends = append(users[0].Friends, &users[1])
+	// db.Where(&users[0]).Association("Friends").Append(&users[1])
+	// db.Save(&users)
+	for _, user := range users {
+		var friends []User
+		db.Model(&user).Association("Friends").Find(&friends)
+		var friendsID []uint
+		for _, friend := range friends {
+			friendsID = append(friendsID, friend.ID)
+		}
+		fmt.Printf("#%d %s, friends=%v\n", user.ID, user.Username, friendsID)
+	}
+}