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

整理了函数,修改了login

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