80 lines
1.8 KiB
Go
Executable File
80 lines
1.8 KiB
Go
Executable File
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"gitea.inhome.blapointe.com/local/oauth2"
|
|
"gitea.inhome.blapointe.com/local/router"
|
|
"gitea.inhome.blapointe.com/local/storage"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func (s *Server) authorize(w http.ResponseWriter, r *http.Request) {
|
|
scope := ""
|
|
router.Params(r, &scope)
|
|
s.limiter.Wait(r.Context())
|
|
if r.Method != "POST" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
id := scope + "." + r.FormValue("username")
|
|
user, ok := s.getUser(id)
|
|
if !ok {
|
|
http.Error(w, "unknown user", http.StatusForbidden)
|
|
return
|
|
}
|
|
access, ok := s.getAccess(scope, user)
|
|
if !ok {
|
|
http.Error(w, "no oauth for user", http.StatusForbidden)
|
|
return
|
|
}
|
|
q := r.URL.Query()
|
|
redirect := q.Get(oauth2.REDIRECT)
|
|
q.Del(oauth2.REDIRECT)
|
|
r.URL.RawQuery = q.Encode()
|
|
if redirect != "" {
|
|
url, _ := url.Parse(redirect)
|
|
if url.Scheme == "" {
|
|
url.Scheme = "http"
|
|
}
|
|
cookie := &http.Cookie{
|
|
Name: oauth2.NEWCOOKIE,
|
|
Value: access,
|
|
Path: "/",
|
|
Domain: "." + strings.Join(strings.Split(strings.Split(url.Host, ":")[0], ".")[1:], "."),
|
|
}
|
|
http.SetCookie(w, cookie)
|
|
http.Redirect(w, r, url.String(), http.StatusSeeOther)
|
|
} else {
|
|
fmt.Fprintln(w, "OK")
|
|
}
|
|
}
|
|
|
|
func (s *Server) genAuth(scope, user string) {
|
|
access := uuid.New().String()
|
|
s.store.Set(user, []byte(access), ACCESS)
|
|
s.store.Set(user, []byte(user), ACCESS)
|
|
s.store.Set(access, []byte(user), ACCESS)
|
|
}
|
|
|
|
func (s *Server) getAccess(scope, user string) (string, bool) {
|
|
access, err := s.store.Get(user, ACCESS)
|
|
if err == storage.ErrNotFound {
|
|
s.genAuth(scope, user)
|
|
access, err = s.store.Get(user, ACCESS)
|
|
}
|
|
return string(access), err == nil
|
|
}
|
|
|
|
func (s *Server) verifyAccess(access string) error {
|
|
_, err := s.store.Get(access, ACCESS)
|
|
if err != nil {
|
|
return fmt.Errorf("access not found: %s", access)
|
|
}
|
|
return nil
|
|
}
|