Beispiel #1
0
Datei: api.go Projekt: siim-/siil
//Provide information about the active id card user
func handleAPIMeRequest(rw http.ResponseWriter, rq *http.Request) {
	switch rq.Method {
	case "GET":
		if !cert.ClientVerified(rq) {
			http.Error(rw, "Certificate not provided", http.StatusBadRequest)
		} else {
			if c, err := cert.NewCertFromRequest(rq); err != nil {
				http.Error(rw, "Certificate not provided", http.StatusBadRequest)
			} else {
				if clientId := rq.FormValue("client_id"); len(clientId) == 0 {
					http.Error(rw, "Invalid client_id provided", http.StatusBadRequest)
				} else {
					//Check origin header validity
					if origin := rq.Header.Get("Origin"); len(origin) != 0 {
						if u, err := url.Parse(origin); err != nil {
							http.Error(rw, "Invalid origin provided", http.StatusBadRequest)
							return
						} else {
							s := site.Entity{Domain: u.Host}
							if err := s.Load(); err == nil && s.ClientId == clientId {
								rw.Header().Set("Access-Control-Allow-Origin", origin)
								rw.Header().Set("Access-Control-Allow-Methods", "GET")
								rw.Header().Set("Access-Control-Allow-Credentials", "true")
							} else {
								http.Error(rw, "Origin not allowed", http.StatusUnauthorized)
								return
							}
						}
					}
					s := site.Entity{ClientId: clientId}
					if err := s.Load(); err != nil {
						http.Error(rw, "Invalid client_id provided", http.StatusBadRequest)
						return
					}
					if usr, err := user.Find(c); err != nil {
						http.Error(rw, "Looks like we don't know you", http.StatusUnauthorized)
					} else {
						if s.HasActiveSessionFor(usr) {
							enc := json.NewEncoder(rw)
							rw.Header().Set("Content-Type", "application/json")
							if err := enc.Encode(usr); err != nil {
								log.Println(err)
								http.Error(rw, "Failed to compose response", http.StatusInternalServerError)
							}
						} else {
							http.Error(rw, "Computer says no", http.StatusUnauthorized)
						}
					}
				}
			}
		}
	default:
		http.Error(rw, "Method not allowed", http.StatusMethodNotAllowed)
	}
}