Esempio n. 1
0
func AccessTokenRequest(data utils.H) (utils.H, error) {
	var user models.User
	var client models.Client

	var code string
	var redirectURI string

	if data["code"] == nil || data["redirect_uri"] == nil || data["client"] == nil {
		return invalidRequestResult("")
	}

	redirectURI = data["redirect_uri"].(string)
	code = data["code"].(string)
	client = data["client"].(models.Client)

	authorizationSession := services.FindSessionByToken(code, models.GrantToken)
	defer services.InvalidateSession(authorizationSession)
	if authorizationSession.ID == 0 {
		return invalidGrantResult("")
	}
	user = authorizationSession.User
	user = services.FindUserByPublicId(user.PublicId)
	if authorizationSession.Client.ID != client.ID {
		return invalidGrantResult("")
	}
	if !strings.Contains(authorizationSession.Client.RedirectURI, redirectURI) {
		return invalidGrantResult("")
	}

	accessToken := services.CreateSession(user,
		client,
		authorizationSession.Ip,
		authorizationSession.UserAgent,
		authorizationSession.Scopes,
		models.AccessToken)
	refreshToken := services.CreateSession(user,
		client,
		authorizationSession.Ip,
		authorizationSession.UserAgent,
		authorizationSession.Scopes,
		models.RefreshToken)

	if accessToken.ID == 0 || refreshToken.ID == 0 {
		return serverErrorResult("")
	}

	return utils.H{
		"user_id":       user.PublicId,
		"access_token":  accessToken.Token,
		"token_type":    "Bearer",
		"expires_in":    accessToken.ExpiresIn,
		"refresh_token": refreshToken.Token,
		"scope":         authorizationSession.Scopes,
	}, nil
}
Esempio n. 2
0
func RefreshTokenRequest(data utils.H) (utils.H, error) {
	var user models.User
	var client models.Client

	var token string
	var scope string

	if data["refresh_token"] == nil || data["scope"] == nil || data["client"] == nil {
		return invalidRequestResult("")
	}

	token = data["refresh_token"].(string)
	scope = data["scope"].(string)
	client = data["client"].(models.Client)

	refreshSession := services.FindSessionByToken(token, models.RefreshToken)
	defer services.InvalidateSession(refreshSession)
	if refreshSession.ID == 0 {
		return invalidGrantResult("")
	}
	user = refreshSession.User
	user = services.FindUserByPublicId(user.PublicId)
	if refreshSession.Client.ID != client.ID {
		return invalidGrantResult("")
	}
	if scope != refreshSession.Scopes {
		return invalidScopeResult("")
	}

	accessToken := services.CreateSession(user,
		client,
		refreshSession.Ip,
		refreshSession.UserAgent,
		scope,
		models.AccessToken)
	refreshToken := services.CreateSession(user,
		client,
		refreshSession.Ip,
		refreshSession.UserAgent,
		scope,
		models.RefreshToken)

	if accessToken.ID == 0 || refreshToken.ID == 0 {
		return serverErrorResult("")
	}

	return utils.H{
		"user_id":       user.PublicId,
		"access_token":  accessToken.Token,
		"token_type":    "Bearer",
		"expires_in":    accessToken.ExpiresIn,
		"refresh_token": refreshToken.Token,
		"scope":         refreshSession.Scopes,
	}, nil
}
Esempio n. 3
0
func ExposeRoutes(router *gin.Engine) {
	router.LoadHTMLGlob("web/templates/*.html")
	router.HTMLRender = createCustomRender()
	if config.IsEnvironment("production") && config.GetConfig("SPACE_CDN") != "" {
		spaceCDN = config.GetConfig("SPACE_CDN")
	} else {
		spaceCDN = "/public"
		router.Static("/public", "web/public")
	}
	store := sessions.NewCookieStore([]byte(config.GetConfig("SPACE_SESSION_SECRET")))
	store.Options(sessions.Options{
		Secure:   config.IsEnvironment("production"),
		HttpOnly: true,
	})
	router.Use(sessions.Sessions("jupiter.session", store))
	views := router.Group("/")
	{
		views.GET("/", jupiterHandler)
		views.GET("/profile", jupiterHandler)

		views.GET("/signup", func(c *gin.Context) {
			c.HTML(http.StatusOK, "satellite", utils.H{
				"AssetsEndpoint": spaceCDN,
				"Title":          " - Sign up",
				"Satellite":      "io",
				"Data": utils.H{
					"feature.gates": utils.H{
						"user.create": feature.Active("user.create"),
					},
				},
			})
		})

		views.GET("/signin", func(c *gin.Context) {
			c.HTML(http.StatusOK, "satellite", utils.H{
				"AssetsEndpoint": spaceCDN,
				"Title":          " - Sign in",
				"Satellite":      "ganymede",
			})
		})

		views.GET("/signout", func(c *gin.Context) {
			session := sessions.Default(c)

			userPublicId := session.Get("userPublicId")
			if userPublicId != nil {
				session.Delete("userPublicId")
				session.Save()
			}

			c.Redirect(http.StatusFound, "/signin")
		})

		views.GET("/session", func(c *gin.Context) {
			session := sessions.Default(c)

			userPublicId := session.Get("userPublicId")
			if userPublicId != nil {
				c.Redirect(http.StatusFound, "/")
				return
			}

			var nextPath string = "/"
			var scope string = c.Query("scope")
			var grantType string = c.Query("grant_type")
			var code string = c.Query("code")
			var clientId string = c.Query("client_id")
			var _nextPath string = c.Query("_")
			//var state string = c.Query("state")

			if scope == "" || grantType == "" || code == "" || clientId == "" {
				// Original response:
				// c.String(http.StatusMethodNotAllowed, "Missing required parameters")
				c.Redirect(http.StatusFound, "/signin")
				return
			}
			if _nextPath != "" {
				if _nextPath, err := url.QueryUnescape(_nextPath); err == nil {
					nextPath = _nextPath
				}
			}

			client := services.FindOrCreateClient("Jupiter")
			if client.Key == clientId && grantType == oauth.AuthorizationCode && scope == models.PublicScope {
				grantToken := services.FindSessionByToken(code, models.GrantToken)
				if grantToken.ID != 0 {
					session.Set("userPublicId", grantToken.User.PublicId)
					session.Save()
					services.InvalidateSession(grantToken)
					c.Redirect(http.StatusFound, nextPath)
					return
				}
			}

			c.Redirect(http.StatusFound, "/signin")
		})

		views.GET("/authorize", authorizeHandler)
		views.POST("/authorize", authorizeHandler)

		views.GET("/error", func(c *gin.Context) {
			errorReason := c.Query("response_type")

			c.HTML(http.StatusOK, "error", utils.H{
				"AssetsEndpoint": spaceCDN,
				"errorReason":    errorReason,
			})
		})

		views.POST("/token", func(c *gin.Context) {
			var grantType string = c.PostForm("grant_type")

			authorizationBasic := strings.Replace(c.Request.Header.Get("Authorization"), "Basic ", "", 1)
			client := oauth.ClientAuthentication(authorizationBasic)
			if client.ID == 0 {
				c.Header("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", c.Request.RequestURI))
				c.JSON(http.StatusUnauthorized, utils.H{
					"error": oauth.AccessDenied,
				})
				return
			}

			switch grantType {
			// Authorization Code Grant
			case oauth.AuthorizationCode:
				result, err := oauth.AccessTokenRequest(utils.H{
					"grant_type":   grantType,
					"code":         c.PostForm("code"),
					"redirect_uri": c.PostForm("redirect_uri"),
					"client":       client,
				})
				if err != nil {
					c.JSON(http.StatusMethodNotAllowed, utils.H{
						"error": result["error"],
					})
					return
				} else {
					c.JSON(http.StatusOK, utils.H{
						"user_id":       result["user_id"],
						"access_token":  result["access_token"],
						"token_type":    result["token_type"],
						"expires_in":    result["expires_in"],
						"refresh_token": result["refresh_token"],
						"scope":         result["scope"],
					})
					return
				}
				return
			// Refreshing an Access Token
			case oauth.RefreshToken:
				result, err := oauth.RefreshTokenRequest(utils.H{
					"grant_type":    grantType,
					"refresh_token": c.PostForm("refresh_token"),
					"scope":         c.PostForm("scope"),
					"client":        client,
				})
				if err != nil {
					c.JSON(http.StatusMethodNotAllowed, utils.H{
						"error": result["error"],
					})
					return
				} else {
					c.JSON(http.StatusOK, utils.H{
						"user_id":       result["user_id"],
						"access_token":  result["access_token"],
						"token_type":    result["token_type"],
						"expires_in":    result["expires_in"],
						"refresh_token": result["refresh_token"],
						"scope":         result["scope"],
					})
					return
				}
				return
			// Resource Owner Password Credentials Grant
			// Client Credentials Grant
			case oauth.Password, oauth.ClientCredentials:
				c.JSON(http.StatusMethodNotAllowed, utils.H{
					"error": oauth.UnsupportedGrantType,
				})
				return
			default:
				c.JSON(http.StatusBadRequest, utils.H{
					"error": oauth.InvalidRequest,
				})
				return
			}
		})
	}
}