示例#1
0
func oauthCallbackHandler(w http.ResponseWriter, r *http.Request) {
	deviceIdC, errDev := r.Cookie("deviceid")
	secretb64C, errSec := r.Cookie("secret")

	if errDev != nil || errSec != nil {
		respondBadRequest(w, "You need to register first.")
	}

	deviceId := deviceIdC.Value
	secretb64 := secretb64C.Value

	Log.Info("Received Callbackrequest for device %s", deviceId)

	if auth.DeviceIdExists(deviceId) && auth.CheckHashedSecret(deviceId, secretb64) {
		Log.Info("Received callback for device %s", deviceId)
		//Get the code from the response
		code := r.FormValue("code")

		// Exchange for token
		token, err := oauthConfig.Exchange(oauth2.NoContext, code)

		if err != nil {
			Log.Error("Could not exchange code to token for device %s")
		}

		err = auth.SaveToken(deviceId, token)
		if err != nil {
			Log.Error("Could not save token for device %s", deviceId)
		}
		Log.Info("Saved token for device %s", deviceId)
		w.Write([]byte("You registered succefully"))
	}
}
示例#2
0
func registerHandler(w http.ResponseWriter, r *http.Request) {
	deviceId := r.PostFormValue("deviceid")
	secret := r.PostFormValue("secret")

	if len(deviceId) < auth.MIN_LEN_DEVICE_ID || len(secret) < auth.MIN_LEN_SECRET {
		respondBadRequest(w, "Arguments have the wrong format")
		return
	}

	Log.Critical("Received register request from device %s", deviceId)

	if auth.DeviceIdExists(deviceId) && auth.DeviceIsConnected(deviceId) {
		respondBadRequest(w, "Device already registered")
		Log.Info("Already registered device %s entered /register", r.Form["deviceId"])
		return
	}

	err := auth.RegisterDevice(deviceId, secret)
	if err != nil {
		Log.Error(err.Error())
	}
	http.SetCookie(w, &http.Cookie{Name: "deviceid", Value: deviceId})
	http.SetCookie(w, &http.Cookie{Name: "secret", Value: auth.HashSecret(secret)})
	// AccessTypeOffline to also retrieve refresh token
	http.Redirect(w, r, oauthConfig.AuthCodeURL("", oauth2.AccessTypeOffline), http.StatusFound)
}