101 lines
2.9 KiB
Go
101 lines
2.9 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/google/uuid"
|
|
"github.com/loveuer/nf"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
// 假设这是你的用户认证函数
|
|
func authenticateUser(username, password string) (bool, error) {
|
|
// 这里你应该实现真实的用户认证逻辑
|
|
// 为了简化,我们这里直接硬编码一个用户名和密码
|
|
if username == "user" && password == "pass" {
|
|
return true, nil
|
|
}
|
|
|
|
return false, fmt.Errorf("invalid username or password")
|
|
}
|
|
|
|
// 处理登录请求
|
|
func handleLogin(c *nf.Ctx) error {
|
|
username := c.FormValue("username")
|
|
password := c.FormValue("password")
|
|
|
|
// 认证用户
|
|
ok, err := authenticateUser(username, password)
|
|
if err != nil || !ok {
|
|
return c.Status(http.StatusUnauthorized).SendString("Unauthorized")
|
|
}
|
|
|
|
// 用户认证成功,重定向到授权页面
|
|
http.Redirect(c.Writer, c.Request, "/authorize?client_id=12345&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&scope=read%20write", http.StatusFound)
|
|
|
|
return nil
|
|
}
|
|
|
|
// 处理授权请求
|
|
func handleAuthorize(c *nf.Ctx) error {
|
|
// 解析查询参数
|
|
clientID := c.Query("client_id")
|
|
responseType := c.Query("response_type")
|
|
redirectURI := c.Query("redirect_uri")
|
|
scope := c.Query("scope")
|
|
|
|
// 检查客户端 ID 和其他参数
|
|
// 在实际应用中,你需要检查这些参数是否合法
|
|
if clientID != "12345" || responseType != "code" || redirectURI != "http://localhost:8080/callback" {
|
|
return c.Status(http.StatusBadRequest).SendString("Invalid request")
|
|
}
|
|
|
|
// 显示授权页面给用户
|
|
_, err := c.Write([]byte(`
|
|
<html>
|
|
<head><title>Authorization</title></head>
|
|
<body>
|
|
<h1>Do you want to authorize this application?</h1>
|
|
<form action="/approve" method="post">
|
|
<input type="hidden" name="client_id" value="` + clientID + `"/>
|
|
<input type="hidden" name="redirect_uri" value="` + redirectURI + `"/>
|
|
<input type="hidden" name="scope" value="` + scope + `"/>
|
|
<button type="submit">Yes, I authorize</button>
|
|
</form>
|
|
</body>
|
|
</html>
|
|
`))
|
|
|
|
return err
|
|
}
|
|
|
|
// 处理用户的授权批准
|
|
func handleApprove(c *nf.Ctx) error {
|
|
// 获取表单数据
|
|
clientID := c.FormValue("client_id")
|
|
redirectURI := c.FormValue("redirect_uri")
|
|
scope := c.FormValue("scope")
|
|
|
|
// 生成授权码
|
|
authorizationCode := uuid.New().String()[:8]
|
|
|
|
log.Printf("[D] client_id = %s, scope = %s, auth_code = %s", clientID, scope, authorizationCode)
|
|
|
|
// 重定向到回调 URL 并附带授权码
|
|
http.Redirect(c.Writer, c.Request, redirectURI+"?code="+authorizationCode, http.StatusFound)
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
app := nf.New()
|
|
|
|
// 设置路由
|
|
app.Get("/login", handleLogin)
|
|
app.Get("/authorize", handleAuthorize)
|
|
app.Post("/approve", handleApprove)
|
|
|
|
// 启动 HTTP 服务器
|
|
log.Println("Starting server on :8080")
|
|
log.Fatal(app.Run(":8080"))
|
|
}
|