Beispiel #1
0
func Server() {
	datastore.Start()
	router := gin.Default()
	web.ExposeRoutes(router)
	restApi := router.Group("/api")
	api.ExposeRoutes(restApi)
	router.Run(fmt.Sprintf(":%v", config.GetConfig("PORT")))
}
Beispiel #2
0
func SendEmail(subject, body, mail_to string) error {
	mail_key := strings.Split(config.GetConfig("SPACE_MAIL_ACCESS"), ":")
	mail_from := config.GetConfig("SPACE_MAIL_FROM")
	sess, err := session.NewSession(&aws.Config{
		Region:      aws.String(mail_key[2]),
		Credentials: credentials.NewStaticCredentials(mail_key[0], mail_key[1], ""),
	})
	if err != nil {
		return err
	}

	svc := ses.New(sess)
	params := &ses.SendEmailInput{
		Source: aws.String(mail_from),
		Destination: &ses.Destination{
			ToAddresses: []*string{
				aws.String(mail_to),
			},
		},
		Message: &ses.Message{
			Subject: &ses.Content{
				Data:    aws.String(subject),
				Charset: aws.String("utf-8"),
			},
			Body: &ses.Body{
				Html: &ses.Content{
					Data:    aws.String(body),
					Charset: aws.String("utf-8"),
				},
			},
		},
		ReplyToAddresses: []*string{
			aws.String(mail_from),
		},
	}
	if _, err := svc.SendEmail(params); err != nil {
		return err
	}

	return nil
}
Beispiel #3
0
func GetDataStoreConnection() *gorm.DB {
	if dataStore != nil {
		return dataStore
	}
	var err error
	var databaseName = fmt.Sprintf("%v_%v",
		config.GetConfig("SPACE_DATASTORE_NAME_PREFIX"), config.Environment())
	var databaseConnectionData = fmt.Sprintf("host=%s user=%s dbname=%s sslmode=%s password=%s",
		config.GetConfig("SPACE_DATASTORE_HOST"),
		config.GetConfig("SPACE_DATASTORE_USER"),
		databaseName,
		config.GetConfig("SPACE_DATASTORE_SSL_MODE"),
		config.GetConfig("SPACE_DATASTORE_PASSWORD"),
	)
	fmt.Printf("Connected to the following data store: %v\n", databaseConnectionData)
	dataStore, err = gorm.Open("postgres", databaseConnectionData)
	if err != nil {
		panic(fmt.Sprintf("Failed to connect datastore: %v\n", err))
	}
	return dataStore
}
Beispiel #4
0
func Start() {
	var err error
	var storeURI string
	if config.IsEnvironment("production") {
		storeURI = fmt.Sprintf("redis://:%v@%v:%v/%v",
			config.GetConfig("SPACE_MEMORYSTORE_PASSWORD"),
			config.GetConfig("SPACE_MEMORYSTORE_HOST"),
			config.GetConfig("SPACE_MEMORYSTORE_PORT"),
			config.GetConfig("SPACE_MEMORYSTORE_INDEX"))
	} else {
		storeURI = fmt.Sprintf("redis://%v:%v/%v",
			config.GetConfig("SPACE_MEMORYSTORE_HOST"),
			config.GetConfig("SPACE_MEMORYSTORE_PORT"),
			config.GetConfig("SPACE_MEMORYSTORE_INDEX"))
	}
	memoryStore, err = redis.DialURL(storeURI)
	if err != nil {
		panic(err)
	}
}
Beispiel #5
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
			}
		})
	}
}
Beispiel #6
0
func defaultKey() []byte {
	keyString := config.GetConfig("SPACE_STORAGE_SECRET")
	return []byte(keyString)
}