<commit_before>package web

import (
	"encoding/json"
	"fmt"
	"github.com/RangelReale/osin"
	"github.com/goods/httpbuf"
	"log"
	"net/http"
	"net/url"
	"tuluu.com/liut/staffio/backends"
	"tuluu.com/liut/staffio/models"
	. "tuluu.com/liut/staffio/settings"
)

// Authorization code endpoint
func oauthAuthorize(w http.ResponseWriter, r *http.Request, ctx *Context) (err error) {
	resp := server.NewResponse()
	defer resp.Close()

	if ar := server.HandleAuthorizeRequest(resp, r); ar != nil {

		link := fmt.Sprintf("/authorize?response_type=%s&client_id=%s&state=%s&redirect_uri=%s",
			ar.Type, ar.Client.GetId(), ar.State, url.QueryEscape(ar.RedirectUri))
		// HANDLE LOGIN PAGE HERE
		if ctx.User == nil {
			ctx.Referer = link
			return loginForm(w, r, ctx)
			// resp.SetRedirect(reverse("login") + "?referer=" + reverse("authorize"))
		} else {
			if r.Method == "GET" {
				scopes, err := backends.LoadScopes()
				if err != nil {
					return err
				}
				return T("authorize.html").Execute(w, map[string]interface{}{
					"link":          link,
					"response_type": ar.Type,
					"scopes":        scopes,
					"client":        ar.Client.(*models.Client),
					"ctx":           ctx,
				})
			}

			if r.PostForm.Get("authorize") == "1" {
				ar.UserData = ctx.User.Uid
				ar.Authorized = true
				server.FinishAuthorizeRequest(resp, r, ar)
			} else {
				resp.SetRedirect(reverse("welcome"))
			}

		}

	}

	if resp.IsError && resp.InternalError != nil {
		log.Printf("authorize ERROR: %s\n", resp.InternalError)
	}
	// if !resp.IsError {
	// 	resp.Output["uid"] = ctx.User.Uid
	// }

	osin.OutputJSON(resp, w, r)
	return resp.InternalError
}

// Access token endpoint
func oauthToken(w http.ResponseWriter, r *http.Request, ctx *Context) (err error) {
	resp := server.NewResponse()
	defer resp.Close()

	var (
		uid  string = ""
		user *User
	)
	if ar := server.HandleAccessRequest(resp, r); ar != nil {
		switch ar.Type {
		case osin.AUTHORIZATION_CODE:
			uid = ar.UserData.(string)
			staff, err := backends.GetStaff(uid)
			if err != nil {
				resp.SetError("get_user_error", "staff not found")
				resp.InternalError = err
			} else {
				user = UserFromStaff(staff)
			}
			ar.Authorized = true
		case osin.REFRESH_TOKEN:
			ar.Authorized = true
		case osin.PASSWORD:
			if Settings.HttpListen == "localhost:3000" && ar.Username == "test" && ar.Password == "<PASSWORD>" {
				ar.Authorized = true
				break
			}

			if !backends.Authenticate(ar.Username, ar.Password) {
				resp.SetError("authentication_failed", err.Error())
				break
			}
			staff, err := backends.GetStaff(ar.Username)
			if err != nil {
				// resp.InternalError = err
				resp.SetError("get_user_failed", err.Error())
				break
			}
			ar.Authorized = true
			ar.UserData = staff.Uid
			user = UserFromStaff(staff)

		case osin.CLIENT_CREDENTIALS:
			ar.Authorized = true
		case osin.ASSERTION:
			if ar.AssertionType == "urn:osin.example.complete" && ar.Assertion == "osin.data" {
				ar.Authorized = true
			}
		}
		server.FinishAccessRequest(resp, r, ar)
	}

	if resp.IsError && resp.InternalError != nil {
		log.Printf("token ERROR: %s\n", resp.InternalError)
	}
	if !resp.IsError {
		if uid != "" {
			resp.Output["uid"] = uid
		}
		if user != nil {
			resp.Output["user"] = user
		}

	}

	osin.OutputJSON(resp, w, r)
	return resp.InternalError
}

// Information endpoint
func oauthInfo(w http.ResponseWriter, r *http.Request, ctx *Context) (err error) {
	resp := server.NewResponse()
	defer resp.Close()

	var (
		uid   string
		user  *User
		topic = ctx.Vars["topic"]
	)
	if ir := server.HandleInfoRequest(resp, r); ir != nil {
		log.Printf("ir Code %s Token %s", ir.Code, ir.AccessData.AccessToken)
		uid = ir.AccessData.UserData.(string)
		staff, err := backends.GetStaff(uid)
		if err != nil {
			resp.SetError("get_user_error", "staff not found")
			resp.InternalError = err
		} else {
			switch topic {
			case "me":
				resp.Output["user"] = UserFromStaff(staff)
			case "staff":
				resp.Output["staff"] = staff
			}

		}
		server.FinishInfoRequest(resp, r, ir)
	}

	if resp.IsError && resp.InternalError != nil {
		log.Printf("info ERROR: %s\n", resp.InternalError)<commit_msg>remove unused defines<commit_after>package web

import (
	"encoding/json"
	"fmt"
	"github.com/RangelReale/osin"
	"github.com/goods/httpbuf"
	"log"
	"net/http"
	"net/url"
	"tuluu.com/liut/staffio/backends"
	"tuluu.com/liut/staffio/models"
	. "tuluu.com/liut/staffio/settings"
)

// Authorization code endpoint
func oauthAuthorize(w http.ResponseWriter, r *http.Request, ctx *Context) (err error) {
	resp := server.NewResponse()
	defer resp.Close()

	if ar := server.HandleAuthorizeRequest(resp, r); ar != nil {

		link := fmt.Sprintf("/authorize?response_type=%s&client_id=%s&state=%s&redirect_uri=%s",
			ar.Type, ar.Client.GetId(), ar.State, url.QueryEscape(ar.RedirectUri))
		// HANDLE LOGIN PAGE HERE
		if ctx.User == nil {
			ctx.Referer = link
			return loginForm(w, r, ctx)
			// resp.SetRedirect(reverse("login") + "?referer=" + reverse("authorize"))
		} else {
			if r.Method == "GET" {
				scopes, err := backends.LoadScopes()
				if err != nil {
					return err
				}
				return T("authorize.html").Execute(w, map[string]interface{}{
					"link":          link,
					"response_type": ar.Type,
					"scopes":        scopes,
					"client":        ar.Client.(*models.Client),
					"ctx":           ctx,
				})
			}

			if r.PostForm.Get("authorize") == "1" {
				ar.UserData = ctx.User.Uid
				ar.Authorized = true
				server.FinishAuthorizeRequest(resp, r, ar)
			} else {
				resp.SetRedirect(reverse("welcome"))
			}

		}

	}

	if resp.IsError && resp.InternalError != nil {
		log.Printf("authorize ERROR: %s\n", resp.InternalError)
	}
	// if !resp.IsError {
	// 	resp.Output["uid"] = ctx.User.Uid
	// }

	osin.OutputJSON(resp, w, r)
	return resp.InternalError
}

// Access token endpoint
func oauthToken(w http.ResponseWriter, r *http.Request, ctx *Context) (err error) {
	resp := server.NewResponse()
	defer resp.Close()

	var (
		uid  string = ""
		user *User
	)
	if ar := server.HandleAccessRequest(resp, r); ar != nil {
		switch ar.Type {
		case osin.AUTHORIZATION_CODE:
			uid = ar.UserData.(string)
			staff, err := backends.GetStaff(uid)
			if err != nil {
				resp.SetError("get_user_error", "staff not found")
				resp.InternalError = err
			} else {
				user = UserFromStaff(staff)
			}
			ar.Authorized = true
		case osin.REFRESH_TOKEN:
			ar.Authorized = true
		case osin.PASSWORD:
			if Settings.HttpListen == "localhost:3000" && ar.Username == "test" && ar.Password == "<PASSWORD>" {
				ar.Authorized = true
				break
			}

			if !backends.Authenticate(ar.Username, ar.Password) {
				resp.SetError("authentication_failed", err.Error())
				break
			}
			staff, err := backends.GetStaff(ar.Username)
			if err != nil {
				// resp.InternalError = err
				resp.SetError("get_user_failed", err.Error())
				break
			}
			ar.Authorized = true
			ar.UserData = staff.Uid
			user = UserFromStaff(staff)

		case osin.CLIENT_CREDENTIALS:
			ar.Authorized = true
		case osin.ASSERTION:
			if ar.AssertionType == "urn:osin.example.complete" && ar.Assertion == "osin.data" {
				ar.Authorized = true
			}
		}
		server.FinishAccessRequest(resp, r, ar)
	}

	if resp.IsError && resp.InternalError != nil {
		log.Printf("token ERROR: %s\n", resp.InternalError)
	}
	if !resp.IsError {
		if uid != "" {
			resp.Output["uid"] = uid
		}
		if user != nil {
			resp.Output["user"] = user
		}

	}

	osin.OutputJSON(resp, w, r)
	return resp.InternalError
}

// Information endpoint
func oauthInfo(w http.ResponseWriter, r *http.Request, ctx *Context) (err error) {
	resp := server.NewResponse()
	defer resp.Close()

	var (
		uid   string
		topic = ctx.Vars["topic"]
	)
	if ir := server.HandleInfoRequest(resp, r); ir != nil {
		log.Printf("ir Code %s Token %s", ir.Code, ir.AccessData.AccessToken)
		uid = ir.AccessData.UserData.(string)
		staff, err := backends.GetStaff(uid)
		if err != nil {
			resp.SetError("get_user_error", "staff not found")
			resp.InternalError = err
		} else {
			switch topic {
			case "me":
				resp.Output["user"] = UserFromStaff(staff)
			case "staff":
				resp.Output["staff"] = staff
			}

		}
		server.FinishInfoRequest(resp, r, ir)
	}

	if resp.IsError && resp.InternalError != nil {
		log.Printf("info ERROR: %s\n", resp.InternalError)
{'fraction_non_alphanumeric': 0.15426041168022978, 'fraction_numerical': 0.0011967448539971278, 'mean_word_length': 3.18687374749499, 'pattern_counts': {'":': 14, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5474926', 'n_tokens_mistral': 3448, 'n_tokens_neox': 3001, 'n_words': 621}