Commit fd162b81 authored by chenhan wang's avatar chenhan wang
Browse files

整理了函数,修改了login

parent ea529607
...@@ -2,11 +2,13 @@ package controller ...@@ -2,11 +2,13 @@ package controller
import ( import (
"backend/model" "backend/model"
"net/http"
"time"
"fmt" "fmt"
"math/rand" "math/rand"
"mime/multipart"
"net/http"
"os" "os"
"time"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
...@@ -22,6 +24,9 @@ func catalogBuild(fileType string) error { ...@@ -22,6 +24,9 @@ func catalogBuild(fileType string) error {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
/*
* generate new uuid
*/
func IdGen(n int) string { func IdGen(n int) string {
b := make([]rune, n) b := make([]rune, n)
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
...@@ -50,15 +55,15 @@ func newAuthenticate(sid string, url string, passwd string) (rsid string, b bool ...@@ -50,15 +55,15 @@ func newAuthenticate(sid string, url string, passwd string) (rsid string, b bool
* 判断用户有无权限访问 * 判断用户有无权限访问
* sid 用cookie 储存传输,如果新生成sid,则保存至cookie * sid 用cookie 储存传输,如果新生成sid,则保存至cookie
*/ */
func Autheticate(cookie *http.Cookie,url string,passwd string) bool { func Autheticate(cookie *http.Cookie, url string, passwd string) bool {
sid:=cookie.Value sid := cookie.Value
if model.Find(sid, url) { if model.Find(sid, url) {
return true return true
} else { } else {
if passwd != "" { if passwd != "" {
var b bool var b bool
sid, b = newAuthenticate(sid, url, passwd) sid, b = newAuthenticate(sid, url, passwd)
cookie.Value=sid cookie.Value = sid
return b return b
} else { } else {
return false return false
...@@ -84,20 +89,19 @@ func GetFileContentType(fileType string) string { ...@@ -84,20 +89,19 @@ func GetFileContentType(fileType string) string {
return StrRet return StrRet
} }
// 设置cookie name sid, value link // 设置cookie name sid, value link
func SetCookie(c echo.Context,cookie *http.Cookie, sid string,maxAge int,time_ time.Time) { func SetCookie(c echo.Context, cookie *http.Cookie, sid string, maxAge int, time_ time.Time) {
cookie.Name = "User" // 标识为user cookie.Name = "User" // 标识为user
//cookie.Value = string(uuid) // 通过uuid和数据库,确定user是谁 //cookie.Value = string(uuid) // 通过uuid和数据库,确定user是谁
cookie.Value = sid cookie.Value = sid
cookie.Path = "/" cookie.Path = "/"
// cookie有效期为3600秒 // cookie有效期为3600秒
if maxAge==0 { if maxAge == 0 {
if time_.IsZero() { if time_.IsZero() {
cookie.MaxAge = 3600 cookie.MaxAge = 3600
} else { } else {
cookie.MaxAge=int(time.Until(time_).Seconds()) cookie.MaxAge = int(time.Until(time_).Seconds())
if cookie.MaxAge<=0 { if cookie.MaxAge <= 0 {
cookie.MaxAge = 3600 cookie.MaxAge = 3600
} }
} }
...@@ -108,43 +112,83 @@ func SetCookie(c echo.Context,cookie *http.Cookie, sid string,maxAge int,time_ t ...@@ -108,43 +112,83 @@ func SetCookie(c echo.Context,cookie *http.Cookie, sid string,maxAge int,time_ t
c.SetCookie(cookie) c.SetCookie(cookie)
} }
func srcRead(c echo.Context, info *File) (src multipart.File, err error) {
file, err := c.FormFile("file")
if err != nil {
logrus.Println(err)
return nil, err
}
// 打开用户上传的文件
src, err = file.Open()
if err != nil {
logrus.Println(err)
return nil, err
}
defer src.Close()
func dstCreate(info *File,fileName string) (dst *os.File,filePath string){ if err = c.Bind(info); err != nil {
info.FileType=TypeComplement(info.FileType) logrus.Println(err)
filePath = "./files/" + info.FileType + "/" + fileName return nil, err
}
info.FileName = file.Filename
return src, nil
}
func dstCreate(info *File) (dst *os.File, filePath string) {
info.FileType = TypeComplement(info.FileType)
filePath = "./files/" + info.FileType + "/" + info.FileName
dst, err := os.Create(filePath) dst, err := os.Create(filePath)
if err != nil { if err != nil {
// 是否目录不完整引起的问题 // 是否目录不完整引起的问题
if !os.IsExist(err) { if !os.IsExist(err) {
if catalogBuild(info.FileType) != nil { if catalogBuild(info.FileType) != nil {
logrus.Println(err) logrus.Println(err)
return nil,"" return nil, ""
} }
dst, err = os.Create(filePath) dst, err = os.Create(filePath)
if err != nil { if err != nil {
logrus.Println(err) logrus.Println(err)
return nil,"" return nil, ""
} }
} }
} }
return dst,filePath return dst, filePath
} }
func DBupdate(c echo.Context,filePath string,info *File)(string,string){ /*
url:="http://pastebin/"+IdGen(8) * 判断文件大小是否超过阈值(threshold,单位B)
cookie,_:=c.Cookie("User") */
var sid string func overflow(dst *os.File, threshold int64) bool {
if cookie==nil{ // 获取文件大小,
sid="" fi, err := dst.Stat()
}else{ if err != nil {
sid=cookie.Value logrus.Println(err)
} }
sid,_=newAuthenticate(sid,url,info.Url)
model.Createlink(sid,info.Passwd,url) // 大小比较
model.Savetext(filePath,30,info.Passwd,info.Time,url) if fi.Size() > threshold {
return sid,url return false
} else {
return true
}
} }
func DBupdate(c echo.Context, filePath string, info *File) (string, string) {
url := "http://pastebin/" + IdGen(8)
cookie, _ := c.Cookie("User")
var sid string
if cookie == nil {
sid = ""
} else {
sid = cookie.Value
}
sid, _ = newAuthenticate(sid, url, info.Url)
model.Createlink(sid, info.Passwd, url)
model.Savetext(filePath, 30, info.Passwd, info.Time, url)
return sid, url
}
func readFile(filePath string) string { func readFile(filePath string) string {
src, err := os.Open(filePath) src, err := os.Open(filePath)
...@@ -171,15 +215,13 @@ func readFile(filePath string) string { ...@@ -171,15 +215,13 @@ func readFile(filePath string) string {
return string(data) return string(data)
} }
// 格式化后缀,仿止出错 // 格式化后缀,仿止出错
func TypeComplement(typ string) string{ func TypeComplement(typ string) string {
// 类型判断 // 类型判断
if typ == "" { if typ == "" {
typ = ".txt" typ = ".txt"
}else if typ[0] != '.'{ } else if typ[0] != '.' {
typ="."+typ typ = "." + typ
} }
return typ return typ
} }
\ No newline at end of file
...@@ -2,100 +2,75 @@ package controller ...@@ -2,100 +2,75 @@ package controller
import ( import (
"backend/app/response" "backend/app/response"
"net" "fmt"
"io"
"net/http" "net/http"
"time" "time"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"fmt"
"io"
) )
type File struct { type File struct {
FileName string `json:"fileName"` FileName string `json:"fileName"`
FileType string `json:"fileType"` FileType string `json:"fileType"`
Expiration int `json:"expiration"` Expiration int `json:"expiration"`
User string `json:"user"` User string `json:"user"`
Passwd string `json:"passwd"` Passwd string `json:"passwd"`
Url string `json:"url"` Url string `json:"url"`
Time time.Time `json:"time"` // 用户指定的时间期限 Time time.Time `json:"time"` // 用户指定的时间期限
//Expiry time.Time `json:"expiry"` // 有效期 //Expiry time.Time `json:"expiry"` // 有效期
//Content string `json:"content"` //Content string `json:"content"`
} }
type Text struct { type Text struct {
text string `json:"text"` text string `json:"text"`
} }
func Ping(c echo.Context) error { func Ping(c echo.Context) error {
// just a demo // just test
return response.SendResponse(c, http.StatusOK, "", "pong!") return response.SendResponse(c, http.StatusOK, "", "pong!")
} }
// 接收浏览器发来的文件,把文件储存在.\files\目录下 // 接收浏览器发来的文件,把文件储存在.\files\目录下
// 成功则返回上传成功,否则报错 // 成功则返回上传成功,否则报错
// sessionId不直接绑定,通过cookie传 // sessionId不直接绑定,通过cookie传
func RecvFile(c echo.Context) error { func RecvFile(c echo.Context) error {
file, err := c.FormFile("file") return c.HTML(http.StatusOK, "<p>文件上传失败: 文件大小超过8MB</p>")
if err != nil { }
logrus.Println(err) func RecvFile1(c echo.Context) error {
return err
}
// 打开用户上传的文件
src, err := file.Open()
if err != nil {
logrus.Println(err)
return err
}
defer src.Close()
info := new(File) info := new(File)
if err = c.Bind(info); err != nil { src, err := srcRead(c, info)
logrus.Println(err) if err != nil {
return err return err // log在srcRead里进行
} }
// 创建目标文件,就是我们打算把用户上传的文件保存到什么地方 // 创建目标文件,就是我们打算把用户上传的文件保存到什么地方
// file.Filename 参数指的是我们以用户上传的文件名,作为目标文件名,也就是服务端保存的文件名跟用户上传的文件名一样 // info.Filename 参数指的是我们以用户上传的文件名,作为目标文件名,也就是服务端保存的文件名跟用户上传的文件名一样
dst,filePath:=dstCreate(info,file.Filename) dst, filePath := dstCreate(info)
defer dst.Close() defer dst.Close()
// 获取文件大小
fi, err := dst.Stat()
if err != nil{
logrus.Println(err)
return err
}
// 大小比较 if !overflow(dst, 8*1024*1024) {
if fi.Size() > 8*1024*10224 {
return c.HTML(http.StatusOK, "<p>文件上传失败: 文件大小超过8MB</p>") return c.HTML(http.StatusOK, "<p>文件上传失败: 文件大小超过8MB</p>")
} }
if err != nil {
fmt.Println(err)
return err
}
// 这里将用户上传的文件复制到服务端的目标文件 // 这里将用户上传的文件复制到服务端的目标文件
if _, err = io.Copy(dst, src); err != nil { if _, err = io.Copy(dst, src); err != nil {
logrus.Println(err) logrus.Println(err)
return err return err
} }
// 更新数据库 // 更新数据库
sid,url:=DBupdate(c,filePath,info) sid, url := DBupdate(c, filePath, info)
cookie := new(http.Cookie) cookie := new(http.Cookie)
SetCookie(c,cookie,sid,info.Expiration,info.Time) SetCookie(c, cookie, sid, info.Expiration, info.Time)
return response.SendResponse2(c, http.StatusOK,*cookie, GetFileContentType(info.FileType), fmt.Sprintf("文件上传成功: %s", file.Filename),url) return response.SendResponse2(c, http.StatusOK, *cookie, GetFileContentType(info.FileType), fmt.Sprintf("文件上传成功: %s", info.FileName), url)
} }
/* /*
* 输入:前端提供的文件链接, * 输入:前端提供的文件链接,
* 返回:一个可供URL访问的链接(string) * 返回:一个可供URL访问的链接(string)
* cookie.Value 传sessionId * cookie.Value 传sessionId
*/ */
func SendFile(c echo.Context) error { func SendFile(c echo.Context) error {
info := new(File) info := new(File)
if err := c.Bind(info); err != nil { if err := c.Bind(info); err != nil {
...@@ -103,41 +78,19 @@ func SendFile(c echo.Context) error { ...@@ -103,41 +78,19 @@ func SendFile(c echo.Context) error {
return err return err
} }
cookie,_:=c.Cookie("User") cookie, _ := c.Cookie("User")
if cookie==nil{ if cookie == nil {
c.HTML(http.StatusBadRequest,"没有cookie") c.HTML(http.StatusBadRequest, "没有cookie")
} }
// 鉴权 // 鉴权
if !Autheticate(cookie,info.Url,info.Passwd) { if !Autheticate(cookie, info.Url, info.Passwd) {
return response.SendResponse(c, http.StatusBadRequest, "msg", "", "密码错误") return response.SendResponse(c, http.StatusBadRequest, "msg", "", "密码错误")
} }
info.FileType=TypeComplement(info.FileType) // 格式化后缀,仿止出错 info.FileType = TypeComplement(info.FileType) // 格式化后缀,仿止出错
filePath := "./files/" + info.FileType + "/" + info.FileName + info.FileType filePath := "./files/" + info.FileType + "/" + info.FileName + info.FileType
data := readFile(filePath) data := readFile(filePath)
c.JSON(http.StatusOK, info) c.JSON(http.StatusOK, info)
return response.SendResponse3(c, http.StatusOK,*cookie, GetFileContentType(info.FileType), data) return response.SendResponse3(c, http.StatusOK, *cookie, GetFileContentType(info.FileType), data)
}
func RecvText(c echo.Context) error {
text := new(Text)
if err := c.Bind(text); err != nil {
fmt.Println(err)
return err
}
//return text.text
return nil
}
func SendText(conn net.Conn, text Text) error {
buf := []byte(text.text)
_, err := conn.Write(buf[:])
if err != nil {
fmt.Println(err)
return err
}
return nil
} }
...@@ -3,9 +3,10 @@ package middleware ...@@ -3,9 +3,10 @@ package middleware
import ( import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
//"time" //"time"
"github.com/sirupsen/logrus"
"os"
"io" "io"
"os"
"github.com/sirupsen/logrus"
//"http/net" //"http/net"
//"pastebin_backend/app/controller" //"pastebin_backend/app/controller"
) )
...@@ -13,7 +14,8 @@ import ( ...@@ -13,7 +14,8 @@ import (
func Auth(next echo.HandlerFunc) echo.HandlerFunc { func Auth(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
mylogger(c) mylogger(c)
c.Set("uid", 114514) uid := getUid(c)
c.Set("uid", uid)
return next(c) return next(c)
} }
} }
...@@ -27,7 +29,7 @@ type logInfo struct { ...@@ -27,7 +29,7 @@ type logInfo struct {
/* /*
向文件或 stdout 输出详细的日志,记录用户的 User-Agent、IP 地址、访问时间、访问路径等信息 向文件或 stdout 输出详细的日志,记录用户的 User-Agent、IP 地址、访问时间、访问路径等信息
User-Agent,访问路径,暂且无法实现 User-Agent,访问路径,暂且无法实现
*/ */
func mylogger(c echo.Context) { func mylogger(c echo.Context) {
//c.GET("User-Agent") //c.GET("User-Agent")
...@@ -38,10 +40,28 @@ func mylogger(c echo.Context) { ...@@ -38,10 +40,28 @@ func mylogger(c echo.Context) {
file, err := os.OpenFile("files/sys.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) file, err := os.OpenFile("files/sys.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil { if err != nil {
logrus.Fatalln("Faild to open error logger file:", err) logrus.Fatalln("Faild to open error logger file:", err)
} }
//同时写文件和屏幕 //同时写文件和屏幕
fileAndStdoutWriter := io.MultiWriter(os.Stdout, file) fileAndStdoutWriter := io.MultiWriter(os.Stdout, file)
logrus.SetOutput(fileAndStdoutWriter) logrus.SetOutput(fileAndStdoutWriter)
logrus.WithField("ip", ip).Info("info log") logrus.WithField("ip", ip).Info("info log")
} }
// 检测 uid 是否有效
func isUidValid(uid string) bool {
if uid == "" {
return false
}
return true
}
// 从报文中获得uid
func getUid(c echo.Context) interface{} {
cookie, err := c.Cookie("User")
if err != nil || !isUidValid(cookie.Value) {
logrus.Panicln("uid invalid,使用默认uuid")
return 114514
} else {
return cookie.Value
}
}
...@@ -11,8 +11,8 @@ func addRoutes() { ...@@ -11,8 +11,8 @@ func addRoutes() {
api.Use(middleware.Auth) api.Use(middleware.Auth)
api.GET("/ping", controller.Ping) api.GET("/ping", controller.Ping)
//api.POST("/passwd",controller.AskPasswd) // 密码,返回cookie //api.POST("/passwd",controller.AskPasswd) // 密码,返回cookie
api.POST("/file/recv",controller.RecvFile)// 接收文件 api.POST("/file/recv", controller.RecvFile) // 接收文件
api.POST("/file/send",controller.SendFile) api.POST("/file/send", controller.SendFile)
api.POST("/text/recv",controller.RecvText) //api.POST("/text/recv",controller.RecvText)
api.POST("/text/send",controller.RecvText) //api.POST("/text/send",controller.RecvText)
} }
...@@ -5,10 +5,9 @@ ...@@ -5,10 +5,9 @@
package main package main
import ( import "backend/app"
"backend/app"
//"backend/model" //"backend/model"
)
func main() { func main() {
app.InitLogger() // 初始化logger设置 app.InitLogger() // 初始化logger设置
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment