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

修改了密码方式,鉴权返回问题没有解决

parent 5535c350
...@@ -5,4 +5,5 @@ backend/files ...@@ -5,4 +5,5 @@ backend/files
conf.yaml conf.yaml
docs/** docs/**
**.exe **.exe
files/** files/**
\ No newline at end of file **.log
\ No newline at end of file
No preview for this file type
package controller
import (
"backend/model"
"net/http"
"time"
"fmt"
"math/rand"
"os"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
)
// 如果没有对应文件夹就建立
func catalogBuild(fileType string) error {
err := os.Mkdir("pastebin/backend/files/"+fileType, 0666)
if err != nil {
return err
}
return nil
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func IdGen(n int) string {
b := make([]rune, n)
rand.Seed(time.Now().UnixNano())
//for i:=0;i<n;i++{
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
/*
* 新建一个sid和url的关联,并返回一个bool表示成功与否
* 若无sessionId,生成一个八位sid并返回
*/
func newAuthenticate(sid string, url string, passwd string) (rsid string, b bool) {
if sid == "" {
rsid = IdGen(8)
} else {
rsid = sid
}
b = model.Createlink(rsid, passwd, url)
return rsid, b
}
/*
* 判断用户有无权限访问
* sid 用cookie 储存传输,如果新生成sid,则保存至cookie
*/
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
return b
} else {
return false
}
}
}
/*
* 通过文件扩展名获取ContentType
*/
func GetFileContentType(fileType string) string {
var StrRet string = ""
switch fileType {
case ".txt":
StrRet = "text/plain"
case ".csv":
StrRet = "text/csv"
case ".tex":
StrRet = "application/x-tex"
case ".md":
StrRet = "text/x-markdown"
}
return StrRet
}
// 设置cookie name sid, value link
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 time_.IsZero() {
cookie.MaxAge = 3600
} else {
cookie.MaxAge=int(time.Until(time_).Seconds())
if cookie.MaxAge<=0 {
cookie.MaxAge = 3600
}
}
} else {
cookie.MaxAge = maxAge
}
// 设置cookie
c.SetCookie(cookie)
}
func dstCreate(info *File,fileName string) (dst *os.File,filePath string){
info.FileType=TypeComplement(info.FileType)
filePath = "./files/" + info.FileType + "/" + fileName
dst, err := os.Create(filePath)
if err != nil {
// 是否目录不完整引起的问题
if !os.IsExist(err) {
if catalogBuild(info.FileType) != nil {
logrus.Println(err)
return nil,""
}
dst, err = os.Create(filePath)
if err != nil {
logrus.Println(err)
return nil,""
}
}
}
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
}
func readFile(filePath string) string {
src, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
}
fi, err := src.Stat()
if err != nil {
fmt.Println(err)
}
defer func() {
src.Close()
}()
data := make([]byte, fi.Size())
_, err = src.Read(data)
if err != nil {
fmt.Println(err)
}
// 信息隐去
//c.JSON(http.StatusOK, info)
return string(data)
}
// 格式化后缀,仿止出错
func TypeComplement(typ string) string{
// 类型判断
if typ == "" {
typ = ".txt"
}else if typ[0] != '.'{
typ="."+typ
}
return typ
}
\ No newline at end of file
package controller package controller
import ( import (
"backend/app/response"
"net" "net"
"net/http" "net/http"
"backend/app/response"
"backend/model"
//"error"
"time" "time"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
//"encoding/json"
"fmt" "fmt"
"io" "io"
"math/rand"
"os"
//"github.com/google/uuid"
//"github.com/go-playground/validator"
//"github.com/sirupsen/logrus"
) )
type File struct { type File struct {
...@@ -27,17 +17,12 @@ type File struct { ...@@ -27,17 +17,12 @@ type File struct {
Expiration int `json:"expiration"` Expiration int `json:"expiration"`
User string `json:"user"` User string `json:"user"`
Passwd string `json:"passwd"` Passwd string `json:"passwd"`
SessionId string `json:"sessionId"` Url string `json:"url"`
FileLink string `json:"fileLink"` Time time.Time `json:"time"` // 用户指定的时间期限
//Expiry time.Time `json:"expiry"` // 有效期 //Expiry time.Time `json:"expiry"` // 有效期
//Content string `json:"content"` //Content string `json:"content"`
} }
type pass struct {
SessionId string `json:"sessionId"`
Passwd string `json:"passwd"`
FileLink string `json:"fileLink"`
}
type Text struct { type Text struct {
text string `json:"text"` text string `json:"text"`
...@@ -48,172 +33,96 @@ func Ping(c echo.Context) error { ...@@ -48,172 +33,96 @@ func Ping(c echo.Context) error {
return response.SendResponse(c, http.StatusOK, "", "pong!") return response.SendResponse(c, http.StatusOK, "", "pong!")
} }
// 通过用户名密码来设置cookie
func AskPasswd(c echo.Context) error {
//
info := new(pass)
if err := c.Bind(info); err != nil {
return err
}
if info.Passwd == "" || info.SessionId == "" {
//return c.String(http.StatusBadRequest, "请输入用户名和密码")
c.String(http.StatusBadRequest, "请输入SessionId和密码")
return echo.ErrBadRequest
}
if model.Createlink(info.SessionId, info.Passwd, info.FileLink) == true {
// 成功建立连接
SetCookie(c, info)
return c.String(http.StatusOK, "登录成功")
}
return c.String(http.StatusOK, "登录失败") //
}
// 设置cookie name sid, value link
func SetCookie(c echo.Context, info *pass) error {
cookie := new(http.Cookie)
cookie.Name = "User"// 标识为user
//cookie.Value = string(uuid) // 通过uuid和数据库,确定user是谁
cookie.Value = info.SessionId
cookie.Path = "/"
// cookie有效期为3600秒
cookie.MaxAge = 3600
// 在数据库中加入 cookie记录
// 设置cookie
c.SetCookie(cookie)
return c.String(http.StatusOK, "cookie设置")
}
// 接收浏览器发来的文件,把文件储存在.\files\目录下 // 接收浏览器发来的文件,把文件储存在.\files\目录下
// 成功则返回上传成功,否则报错 // 成功则返回上传成功,否则报错
// sessionId不直接绑定,通过cookie传
func RecvFile(c echo.Context) error { func RecvFile(c echo.Context) error {
file, err := c.FormFile("file") file, err := c.FormFile("file")
if err != nil { if err != nil {
logrus.Println(err)
return err return err
} }
// 打开用户上传的文件 // 打开用户上传的文件
src, err := file.Open() src, err := file.Open()
if err != nil { if err != nil {
logrus.Println(err)
return err return err
} }
defer src.Close() defer src.Close()
info := new(File) info := new(File)
if err = c.Bind(info); err != nil { if err = c.Bind(info); err != nil {
logrus.Println(err)
return err return err
} }
// 创建目标文件,就是我们打算把用户上传的文件保存到什么地方 // 创建目标文件,就是我们打算把用户上传的文件保存到什么地方
// file.Filename 参数指的是我们以用户上传的文件名,作为目标文件名,也就是服务端保存的文件名跟用户上传的文件名一样 // file.Filename 参数指的是我们以用户上传的文件名,作为目标文件名,也就是服务端保存的文件名跟用户上传的文件名一样
if info.FileType == "" { dst,filePath:=dstCreate(info,file.Filename)
info.FileType = "txt" defer dst.Close()
}
filePath := "./files/" + info.FileType + "/" + file.Filename
dst, err := os.Create(filePath)
if err != nil {
// 是否目录不完整引起的问题
if os.IsExist(err) == false {
if catalogBuild(info.FileType) != nil {
return err
}
dst, err = os.Create(filePath)
if err != nil {
return err
}
}
}
// 获取文件大小 // 获取文件大小
fi, _ := dst.Stat() fi, err := dst.Stat()
if err != nil{
logrus.Println(err)
return err
}
// 大小比较
if fi.Size() > 8*1024*10224 { if fi.Size() > 8*1024*10224 {
c.HTML(http.StatusOK, fmt.Sprintf("<p>文件上传失败: 文件大小超过8MB</p>")) return c.HTML(http.StatusOK, "<p>文件上传失败: 文件大小超过8MB</p>")
} }
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
return err return err
} }
defer dst.Close()
// 这里将用户上传的文件复制到服务端的目标文件 // 这里将用户上传的文件复制到服务端的目标文件
if _, err = io.Copy(dst, src); err != nil { if _, err = io.Copy(dst, src); err != nil {
logrus.Println(err)
return err return err
} }
// 更新数据库 // 更新数据库
dinfo := model.Users{ sid,url:=DBupdate(c,filePath,info)
Username: info.User, cookie := new(http.Cookie)
Passwd: info.Passwd, SetCookie(c,cookie,sid,info.Expiration,info.Time)
Name: info.FileName, // 无后缀 return response.SendResponse2(c, http.StatusOK,*cookie, GetFileContentType(info.FileType), fmt.Sprintf("文件上传成功: %s", file.Filename),url)
Size: uint(fi.Size()),
Route: filePath,
//Time1: info.Expiry,
}
model.Createuser(dinfo) // 数据库一条新纪录
return c.HTML(http.StatusOK, fmt.Sprintf("<p>文件上传成功: %s</p>", file.Filename))
} }
/* /*
输入:前端提供的文件链接, * 输入:前端提供的文件链接,
返回:一个可供URL访问的链接(string) * 返回:一个可供URL访问的链接(string)
* 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 {
logrus.Println(err)
return err return err
} }
// 判断需不需要密码 cookie,_:=c.Cookie("User")
if info.FileType == "" { if cookie==nil{
info.FileType = "txt" c.HTML(http.StatusBadRequest,"没有cookie")
} }
if !model.Find(info.FileLink, info.SessionId) { // 鉴权
// 没有sessionId(第一次访问) if !Autheticate(cookie,info.Url,info.Passwd) {
cookie, err := c.Cookie("User") return response.SendResponse(c, http.StatusBadRequest, "msg", "", "密码错误")
if err != nil {
return err
}
if cookie.Value != info.FileLink {
return err // you wenti
}
} }
filePath := "./files/" + info.FileType + "/" + info.FileName + "." + info.FileType info.FileType=TypeComplement(info.FileType) // 格式化后缀,仿止出错
data:=readFile(filePath) filePath := "./files/" + info.FileType + "/" + info.FileName + info.FileType
data := readFile(filePath)
c.JSON(http.StatusOK, info) c.JSON(http.StatusOK, info)
return response.SendResponse(c, http.StatusOK, "msg",info.FileType, data) return response.SendResponse3(c, http.StatusOK,*cookie, GetFileContentType(info.FileType), data)
//return c.HTML(http.StatusOK, fmt.Sprintf("<p>文件上传成功: %s</p>", file.Filename))
//return nil
} }
func readFile(filePath string) string{
src, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
}
fi, err := src.Stat()
if err != nil {
fmt.Println(err)
}
defer func() {
src.Close()
}()
data := make([]byte, fi.Size())
_, err = src.Read(data)
if err != nil {
fmt.Println(err)
}
// 信息隐去
//c.JSON(http.StatusOK, info)
return string(data)
}
func RecvText(c echo.Context) error {
func RecvText(c echo.Context) error {
text := new(Text) text := new(Text)
if err := c.Bind(text); err != nil { if err := c.Bind(text); err != nil {
fmt.Println(err) fmt.Println(err)
...@@ -232,24 +141,3 @@ func SendText(conn net.Conn, text Text) error { ...@@ -232,24 +141,3 @@ func SendText(conn net.Conn, text Text) error {
} }
return nil return nil
} }
// 如果没有对应文件夹就建立
func catalogBuild(fileType string) error {
err := os.Mkdir("pastebin/backend/files/"+fileType, 0666)
if err != nil {
return err
}
return nil
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func IdGen(n int) string {
b := make([]rune, n)
rand.Seed(time.Now().UnixNano())
//for i:=0;i<n;i++{
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
...@@ -27,4 +27,17 @@ func StartServer() { ...@@ -27,4 +27,17 @@ func StartServer() {
} }
/*
* 初始化logger设置
*/
func InitLogger(){
//自定义日志格式
logrus.SetFormatter(&logrus.TextFormatter{
ForceQuote:true, //键值对加引号
TimestampFormat:"2006-01-02 15:04:05", //时间格式
FullTimestamp:true,
})
logrus.SetReportCaller(true)
}
...@@ -3,8 +3,9 @@ package middleware ...@@ -3,8 +3,9 @@ package middleware
import ( import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
//"time" //"time"
"log" "github.com/sirupsen/logrus"
"os" "os"
"io"
//"http/net" //"http/net"
//"pastebin_backend/app/controller" //"pastebin_backend/app/controller"
) )
...@@ -34,12 +35,13 @@ func mylogger(c echo.Context) { ...@@ -34,12 +35,13 @@ func mylogger(c echo.Context) {
ip := echo.ExtractIPDirect()(c.Request()) ip := echo.ExtractIPDirect()(c.Request())
//日志输出文件 //日志输出文件
file, err := os.OpenFile("backend/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 {
log.Fatalln("Faild to open error logger file:", err) logrus.Fatalln("Faild to open error logger file:", err)
} }
//自定义日志格式 //同时写文件和屏幕
Info := log.New(file, "[Info]", log.Llongfile) fileAndStdoutWriter := io.MultiWriter(os.Stdout, file)
Info.SetFlags(log.Ldate | log.Ltime) logrus.SetOutput(fileAndStdoutWriter)
Info.Println(ip) logrus.WithField("ip", ip).Info("info log")
} }
...@@ -13,6 +13,15 @@ type Response struct { ...@@ -13,6 +13,15 @@ type Response struct {
Data interface{} `json:"data"` Data interface{} `json:"data"`
} }
type Response2 struct {
Code int `json:"code"`
Cookie http.Cookie `json:"cookie"`
Type string `json:"type"`
Url string `json:"url"`
Data interface{} `json:"data"`
}
func SendResponse(c echo.Context, code int, msg string, data ...interface{}) error{ func SendResponse(c echo.Context, code int, msg string, data ...interface{}) error{
return c.JSON(http.StatusOK, Response{ return c.JSON(http.StatusOK, Response{
Code: code, Code: code,
...@@ -20,3 +29,23 @@ func SendResponse(c echo.Context, code int, msg string, data ...interface{}) err ...@@ -20,3 +29,23 @@ func SendResponse(c echo.Context, code int, msg string, data ...interface{}) err
Data: data, Data: data,
}) })
} }
func SendResponse2(c echo.Context, code int,cookie http.Cookie, typ string,url string, data ...interface{}) error{
return c.JSON(http.StatusOK, Response2{
Code: code,
Cookie:cookie,
Type: typ,
Url: url,
Data: data,
})
}
func SendResponse3(c echo.Context, code int,cookie http.Cookie, typ string, data ...interface{}) error{
return c.JSON(http.StatusOK, Response2{
Code: code,
Cookie:cookie,
Type: typ,
Data: data,
})
}
\ No newline at end of file
...@@ -10,7 +10,7 @@ func addRoutes() { ...@@ -10,7 +10,7 @@ func addRoutes() {
api := e.Group("api") api := e.Group("api")
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)
......
test
curl -F api_key=<api_key> -F api_secret=<api_secret> –F image=@test2.txt -F return_portrait=1
curl localhost/api/file/send '{\"fileName\":\"test2.png\"}' -F "file=@./test.png" -H "token:222" -v
curl localhost/api/file/send -d "{\"fileName\":\"test2.png\"}"
curl localhost/api/file/send -F "file=@./test.png" -H "token:222" -v
curl -d 'use=sei' localhost/api/print/query
curl -d '{\"user\":\"jkj\"}' localhost/api/print/query
curl -d "{\"keyword\":\"user\",\"value\":\"wnag\"}" localhost/api/print/query
curl -d "{\"keyword\":\"user\",\"value\":\"wnag\"}" localhost/api/print/body
curl -X POST localhost/api/SQL/adduser -H 'Content-Type: application/json' -d '{"name":"Joe","passwd":"joe@labstack"}'
curl -X POST localhost/api/SQL/adduser -H 'Content-Type: application/json' -d‘{\"name\":\"na\",\"passwd\":\"pass\"}’
curl -X POST localhost/api/SQL/test -H 'Content-Type: application/json' -d‘{\"name\":\"na\",\"passwd\":\"pass\"}’
curl http://127.0.0.1:8080/api/SQL/adduser -X POST -H "Content-Type: application/json" -d {"name":"1","passwd":"934"}
//有效的
curl localhost/api/SQL/adduser -X POST -H "Content-Type: application/json" -d "{\"name\":\"add\",\"passwd\":\"yyy\"}"
{"id":22,"name":"add","passwd":"yyy"}
curl localhost/api/file/recv -F "file=@./test2.txt" -H "token:222" -v
curl localhost/api/file/send -X POST -H "Content-Type: application/json" -d “{\"fileName\":\"test2\",\"fileType\":\"txt\"}”
\ No newline at end of file
...@@ -6,27 +6,13 @@ ...@@ -6,27 +6,13 @@
package main package main
import ( import (
//"backend/app" "backend/app"
//"pastebin_backend/app/controller" //"backend/model"
"backend/model"
//"time"
"fmt"
"github.com/sirupsen/logrus"
) )
func main() { func main() {
logrus.SetReportCaller(true) app.InitLogger() // 初始化logger设置
model.Init() //model.Init()
/* var user3 model.Users app.InitWebFramework()
user3.Passwd = "123456" app.StartServer()
model.Createuser(user3)
var url2 = new(model.Url)
var s2 string = "/person/example"
var s3 string = "lytgodbb"
for i := 0; i <= 10; i++ {
model.Checkt(s2)
}*/
fmt.Println(model.Find("fF2pGKiB","/person/example "))
//controller.BuildSocket()
//controller.RecvFile()
} }
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