Ejemplo n.º 1
1
func AddTemplatingInfo(c *gin.Context) {
	// Get the actual data from the context
	obj := c.MustGet("data").(gin.H)
	// Add the required data
	obj["_static_root"] = Config.Global.Service.Address + "/static"
	// Set the web's title
	obj["_site_title"] = "Sirikon's Lab"
	// And save it again
	c.Set("data", obj)
}
Ejemplo n.º 2
0
func authWithToken(c *gin.Context, userToken string) error {
	token, err := jwt.Parse(userToken, func(token *jwt.Token) (interface{}, error) {
		if jwt.GetSigningMethod("HS256") != token.Method {
			//TODO: "Invalid signing token algorithm."
			return nil, nil
		}

		//TODO: cache this
		tokenSecretRecord, err := db.NewSystemDbService().FindId("accountSecret", nil)

		if err != nil {
			fmt.Println(err.Error())
			//we probably do not have such collection. Use a default secret and warn.
			tokenSecretRecord = JSON{
				"value": "",
			}
		}

		tokenSecret := tokenSecretRecord["value"].(string)

		return []byte(tokenSecret), nil
	})

	c.Set("token", token)
	c.Set("user", token.Claims["user"])

	return err
}
Ejemplo n.º 3
0
func Logger(c *gin.Context) {
	requestId := util.NewId()
	c.Set("request_id", requestId)

	method := c.Request.Method
	path := c.Request.URL.EscapedPath()
	ip := c.ClientIP()

	log.InfoFields("Request received", log.Fields{
		"request_id": requestId,
		"method":     method,
		"ip":         ip,
		"path":       path,
	})

	start := time.Now()
	c.Next()
	duration := time.Since(start)

	code := c.Writer.Status()

	log.InfoFields("Request handled", log.Fields{
		"request_id": requestId,
		"took":       duration.String(),
		"code":       code,
	})

}
Ejemplo n.º 4
0
func TestSetPerm(t *testing.T) {
	g := goblin.Goblin(t)
	g.Describe("SetPerm", func() {
		g.BeforeEach(func() {
			os.Unsetenv("PUBLIC_MODE")
		})
		g.It("Should set pull to false (private repo, user not logged in)", func() {
			c := gin.Context{}
			c.Set("repo", &model.Repo{
				IsPrivate: true,
			})
			SetPerm()(&c)
			v, ok := c.Get("perm")
			g.Assert(ok).IsTrue("perm was not set")
			p, ok := v.(*model.Perm)
			g.Assert(ok).IsTrue("perm was the wrong type")
			g.Assert(p.Pull).IsFalse("pull should be false")
		})
		g.It("Should set pull to true (private repo, user not logged in, public mode)", func() {
			os.Setenv("PUBLIC_MODE", "true")
			c := gin.Context{}
			c.Set("repo", &model.Repo{
				IsPrivate: true,
			})
			SetPerm()(&c)
			v, ok := c.Get("perm")
			g.Assert(ok).IsTrue("perm was not set")
			p, ok := v.(*model.Perm)
			g.Assert(ok).IsTrue("perm was the wrong type")
			g.Assert(p.Pull).IsTrue("pull should be true")
		})
	})
}
Ejemplo n.º 5
0
func GroupCheck(tc *ginoauth2.TokenContainer, access_tuple []ginoauth2.AccessTuple, ctx *gin.Context) bool {
	blob, err := RequestTeamInfo(tc, TeamAPI)
	if err != nil {
		glog.Error("failed to get team info, caused by: ", err)
		return false
	}
	var data []TeamInfo
	err = json.Unmarshal(blob, &data)
	if err != nil {
		glog.Errorf("JSON.Unmarshal failed, caused by: %s", err)
		return false
	}
	for _, teamInfo := range data {
		for idx := range access_tuple {
			at := access_tuple[idx]
			if teamInfo.Id_name == at.Uid {
				ctx.Set("uid", tc.Scopes["uid"].(string))
				ctx.Set("team", teamInfo.Id_name)
				glog.Infof("Grant access to %s as team member of %s\n", tc.Scopes["uid"].(string), teamInfo.Id_name)
				return true
			}
		}
	}

	return false
}
Ejemplo n.º 6
0
func TestReposCache(t *testing.T) {

	g := goblin.Goblin(t)
	g.Describe("Repo List Cache", func() {

		var c *gin.Context
		g.BeforeEach(func() {
			c = new(gin.Context)
			cache.ToContext(c, cache.Default())
		})

		g.It("should skip when no user session", func() {
			Perms(c)

			_, ok := c.Get("perm")
			g.Assert(ok).IsFalse()
		})

		g.It("should get repos from cache", func() {
			c.Set("user", fakeUser)
			cache.SetRepos(c, fakeUser, fakeRepos)

			Repos(c)

			repos, ok := c.Get("repos")
			g.Assert(ok).IsTrue()
			g.Assert(repos).Equal(fakeRepos)
		})

	})
}
Ejemplo n.º 7
0
func AuthCheck(c *gin.Context) {
	id, _ := c.Get("request_id")
	log.InfoFields("Checking auth token", log.Fields{
		"request_id": id,
	})

	token := c.Query("token")
	if token == "" {
		tokenHeaders := c.Request.Header["Token"]
		if len(tokenHeaders) == 0 {
			c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("No notion access token provided"))
			return
		} else {
			token = tokenHeaders[0]
		}
	}

	in, user, err := db.GetUserByToken(token)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("Internal server error"))
		return
	}
	if !in {
		c.AbortWithError(http.StatusUnauthorized, fmt.Errorf("Notion access token provided is not currently valid"))
		return
	}

	c.Set("request_user_id", user.Id)
}
Ejemplo n.º 8
0
// Repos is a middleware function that attempts to cache the
// user's list of remote repositories (ie in GitHub) to minimize
// remote calls that might be expensive, slow or rate-limited.
func Repos(c *gin.Context) {
	var user, _ = c.Get("user")

	if user == nil {
		c.Next()
		return
	}

	// if the item already exists in the cache
	// we can continue the middleware chain and
	// exit afterwards.
	v := cache.GetRepos(c, user.(*model.User))
	if v != nil {
		c.Set("repos", v)
		c.Next()
		return
	}

	// otherwise, if the item isn't cached we execute
	// the middleware chain and then cache the permissions
	// after the request is processed.
	c.Next()

	repos, ok := c.Get("repos")
	if ok {
		cache.SetRepos(c,
			user.(*model.User),
			repos.([]*model.RepoLite),
		)
	}
}
Ejemplo n.º 9
0
// http://blog.mongodb.org/post/80579086742/running-mongodb-queries-concurrently-with-go
// Request a socket connection from the session to process our query.
// Close the session when the goroutine exits and put the connection
// back
// into the pool.
func (session *DatabaseSession) Database(c *gin.Context) {
	s := session.Clone()
	defer s.Close()

	c.Set("mongo_session", s.DB(session.databaseName))
	c.Next()
}
Ejemplo n.º 10
0
func EnvironmentMiddleware(c *gin.Context) {
	project := c.MustGet("project").(models.Project)
	envID, err := util.GetIntParam("environment_id", c)
	if err != nil {
		return
	}

	query, args, _ := squirrel.Select("*").
		From("project__environment").
		Where("project_id=?", project.ID).
		Where("id=?", envID).
		ToSql()

	var env models.Environment
	if err := database.Mysql.SelectOne(&env, query, args...); err != nil {
		if err == sql.ErrNoRows {
			c.AbortWithStatus(404)
			return
		}

		panic(err)
	}

	c.Set("environment", env)
	c.Next()
}
Ejemplo n.º 11
0
// GroupCheck is an authorization function that checks, if the Token
// was issued for an employee of a specified team. The given
// TokenContainer must be valid.
func GroupCheck(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool {
	blob, err := RequestTeamInfo(tc, TeamAPI)
	if err != nil {
		glog.Error("failed to get team info, caused by: ", err)
		return false
	}
	var data []TeamInfo
	err = json.Unmarshal(blob, &data)
	if err != nil {
		glog.Errorf("JSON.Unmarshal failed, caused by: %s", err)
		return false
	}
	granted := false
	for _, teamInfo := range data {
		for idx := range AccessTuples {
			at := AccessTuples[idx]
			if teamInfo.Id == at.Uid {
				granted = true
				glog.Infof("Grant access to %s as team member of \"%s\"\n", tc.Scopes["uid"].(string), teamInfo.Id)
			}
			if teamInfo.Type == "official" {
				ctx.Set("uid", tc.Scopes["uid"].(string))
				ctx.Set("team", teamInfo.Id)
			}
		}
	}
	return granted
}
Ejemplo n.º 12
0
func bindArtifact(ctx context.Context, r render.Render, gc *gin.Context, db database.Database) *model.Artifact {
	bucketId := gc.Param("bucket_id")
	artifactName := gc.Param("artifact_name")
	artifact, err := db.GetArtifactByName(bucketId, artifactName)

	if err != nil && err.EntityNotFound() {
		api.LogAndRespondWithErrorf(ctx, r, http.StatusNotFound, "Artifact not found")
		gc.Abort()
		return nil
	}

	if err != nil {
		api.LogAndRespondWithError(ctx, r, http.StatusInternalServerError, err)
		gc.Abort()
		return nil
	}

	if artifact == nil {
		api.LogAndRespondWithErrorf(ctx, r, http.StatusBadRequest, "Got nil artifact without error for artifact: %s/%s", bucketId, artifactName)
		gc.Abort()
		return nil
	}

	gc.Set("artifact", artifact)
	return artifact
}
Ejemplo n.º 13
0
func bindBucket(ctx context.Context, r render.Render, gc *gin.Context, db database.Database) {
	bucketId := gc.Param("bucket_id")
	bucket, err := db.GetBucket(bucketId)

	if err != nil && err.EntityNotFound() {
		// Don't log this error to Sentry
		// Changes will hit this endpoint for non-existant buckets very often.
		api.RespondWithErrorf(ctx, r, http.StatusNotFound, "Bucket not found")
		gc.Abort()
		return
	}

	if err != nil {
		api.LogAndRespondWithError(ctx, r, http.StatusInternalServerError, err)
		gc.Abort()
		return
	}

	if bucket == nil {
		api.LogAndRespondWithErrorf(ctx, r, http.StatusBadRequest, "Got nil bucket without error for bucket: %s", bucketId)
		gc.Abort()
		return
	}

	gc.Set("bucket", bucket)
}
Ejemplo n.º 14
0
func InventoryMiddleware(c *gin.Context) {
	project := c.MustGet("project").(models.Project)
	inventoryID, err := util.GetIntParam("inventory_id", c)
	if err != nil {
		return
	}

	query, args, _ := squirrel.Select("*").
		From("project__inventory").
		Where("project_id=?", project.ID).
		Where("id=?", inventoryID).
		ToSql()

	var inventory models.Inventory
	if err := database.Mysql.SelectOne(&inventory, query, args...); err != nil {
		if err == sql.ErrNoRows {
			c.AbortWithStatus(404)
			return
		}

		panic(err)
	}

	c.Set("inventory", inventory)
	c.Next()
}
Ejemplo n.º 15
0
func ProjectMiddleware(c *gin.Context) {
	user := c.MustGet("user").(*models.User)

	projectID, err := util.GetIntParam("project_id", c)
	if err != nil {
		return
	}

	query, args, _ := squirrel.Select("p.*").
		From("project as p").
		Join("project__user as pu on pu.project_id=p.id").
		Where("p.id=?", projectID).
		Where("pu.user_id=?", user.ID).
		ToSql()

	var project models.Project
	if err := database.Mysql.SelectOne(&project, query, args...); err != nil {
		if err == sql.ErrNoRows {
			c.AbortWithStatus(404)
			return
		}

		panic(err)
	}

	c.Set("project", project)
	c.Next()
}
Ejemplo n.º 16
0
func GetRepos(c *gin.Context) {
	user := session.User(c)
	remote := remote.FromContext(c)
	var repos []*model.RepoLite

	// get the repository list from the cache
	reposv, ok := c.Get("repos")
	if ok {
		repos = reposv.([]*model.RepoLite)
	} else {
		var err error
		repos, err = remote.Repos(user)
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
	}

	// for each repository in the remote system we get
	// the intersection of those repostiories in Drone
	repos_, err := store.GetRepoListOf(c, repos)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	c.Set("repos", repos)
	c.IndentedJSON(http.StatusOK, repos_)
}
Ejemplo n.º 17
0
func SetUser(c *gin.Context) {
	var user *model.User

	// authenticates the user via an authentication cookie
	// or an auth token.
	t, err := token.ParseRequest(c.Request, func(t *token.Token) (string, error) {
		var err error
		user, err = store.GetUserLogin(c, t.Text)
		return user.Secret, err
	})

	if err == nil {
		c.Set("user", user)

		// if this is a session token (ie not the API token)
		// this means the user is accessing with a web browser,
		// so we should implement CSRF protection measures.
		if t.Kind == token.SessToken {
			err = token.CheckCsrf(c.Request, func(t *token.Token) (string, error) {
				return user.Secret, nil
			})
			// if csrf token validation fails, exit immediately
			// with a not authorized error.
			if err != nil {
				c.AbortWithStatus(http.StatusUnauthorized)
				return
			}
		}
	}
	c.Next()
}
Ejemplo n.º 18
0
// PreAbort sets the appropriate error JSON after starting the persistence.
func (m AnalyticsToken) PreAbort(c *gin.Context, auth *headerauth.AuthInfo, err *headerauth.AuthErr) {
	m.wg.Add(1)
	c.Set(m.ContextKey(), auth.AccessKey)
	c.Set("authSuccess", false)
	m.persistC <- NewS3Persist("analytics", false, c)
	c.JSON(err.Status, StatusMsg[err.Status].JSON())
}
Ejemplo n.º 19
0
//LocaleHandler handler for detcte locale
func LocaleHandler(c *gin.Context) {
	// written := false
	// 1. Check URL arguments.
	lng := c.Request.URL.Query().Get("locale")

	// 2. Get language information from cookies.
	if len(lng) == 0 {
		if ck, er := c.Request.Cookie("locale"); er == nil {
			lng = ck.Value
		}
	}
	// else {
	// 	written = true
	// }

	// 3. Get language information from 'Accept-Language'.
	if len(lng) == 0 {
		al := c.Request.Header.Get("Accept-Language")
		if len(al) > 4 {
			lng = al[:5]
		}
	}

	tag := Match(lng)

	// if written {
	// 	c.SetCookie("locale", tag.String(), 1<<31-1, "/", "", false, false)
	// }
	c.Set("locale", tag.String())
}
Ejemplo n.º 20
0
// Connect middleware clones the database session for each request and
// makes the `db` object available for each handler
func Connect(c *gin.Context) {
	s := db.Session.Clone()

	defer s.Close()

	c.Set("db", s.DB(db.Mongo.Database))
	c.Next()
}
Ejemplo n.º 21
0
func (ss *schedulerService) ValidateID(c *gin.Context) {
	userID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid User Id"})
		c.Abort()
		return
	}
	c.Set("id", userID)
	c.Next()
}
Ejemplo n.º 22
0
func ginExecute(c *gin.Context, handlerChain gin.HandlersChain) {
	c.Set("handlerChain", handlerChain)
	c.Set("gin_next_idx", int8(0))
	handlerChain[0](c)
	ginIdx, _ := c.Keys["gin_next_idx"].(int8)
	s := int8(len(handlerChain))
	for ; ginIdx < s; ginIdx++ {
		handlerChain[ginIdx](c)
	}
}
Ejemplo n.º 23
0
func render(c *gin.Context, template string, ctx map[string]interface{}) {
	config := cfg.GetConfig()

	ctx["instance_id"] = cfg.InstanceId()
	ctx["url_path"] = c.Request.URL.Path
	ctx["date_format"] = config.Ui.DateFormat

	c.Set("template", fmt.Sprintf("%s/templates/%s/%s", cfg.RootDir(), config.Ui.Theme, template))
	c.Set("data", ctx)
	c.Writer.WriteHeader(http.StatusOK)
}
Ejemplo n.º 24
0
func A1MiddleWare(c *gin.Context) {
	obj := &InjectObj{
		val: "cool u,handsome me",
	}
	c.Set("iObj", obj)
	log.Println(" before  next ")
	//	c.Next()
	ginNext(c)
	log.Println(" after  next ")

}
Ejemplo n.º 25
0
// RequestID tag the current request with an ID & add a response X-Request-Id header.
func RequestID(context *gin.Context) {
	// Generate an ID for this request.
	id := uuid.NewV4().String()

	// Bind request ID to context.
	context.Set("request_id", id)
	context.Writer.Header().Set("X-Request-ID", id)

	// Yield to other middleware handlers.
	context.Next()
}
Ejemplo n.º 26
0
func TestBuildTeamLabel(t *testing.T) {
	fakeContext := gin.Context{}
	expectedUID := "rdifazio"
	expectedTeam := "TechMonkeys"
	fakeContext.Set("uid", expectedUID)
	fakeContext.Set("team", expectedTeam)
	team, uid := buildTeamLabel(&fakeContext)
	if uid != expectedUID || team != expectedTeam {
		fmt.Printf("Expected: %s - %s, got: %s, %s", expectedUID, expectedTeam, uid, team)
		t.FailNow()
	}
}
Ejemplo n.º 27
0
func DummyMiddleware(c *gin.Context) {
	c.Set("hello", "world") // mapping obj using map
	uri := c.Request.RequestURI
	if uri == "/dummy2" { // abort the request using middleware
		resp := map[string]string{"figo": "xu"}
		c.JSON(200, resp)
		c.Abort()
		return
	}
	log.Println("Im a dummy!")
	c.Next()
}
Ejemplo n.º 28
0
func Signer(c *gin.Context, s s2tore.SessionStore, u UserStore) error {
	nameParam := c.Params.ByName(NameRequestField)
	tmp, err := base64.StdEncoding.DecodeString(nameParam)
	if err != nil {
		return err
	}
	name := string(tmp)
	passParam := c.Params.ByName(PassRequestField)
	tmp, err = base64.StdEncoding.DecodeString(passParam)
	if err != nil {
		return err
	}
	pass := string(tmp)

	user, err := u.FindUser(name)
	if err != nil {
		return err
	}

	if !user.ValidPassword(pass) {
		return SignInErr
	}

	expire := time.Now().Add(24 * time.Hour)
	session, err := s.NewSession(user.ID(), expire)
	if err != nil {
		return err
	}

	c.Set(GinContextField, session)

	resp := NewSuccessResponse(SessionResponse{
		Token:   session.Token(),
		UserID:  session.UserID(),
		Expires: session.Expires(),
	})

	cookie := http.Cookie{
		Name:    XSRFCookieName,
		Value:   session.Token(),
		Expires: session.Expires(),
		// Setze Path auf / ansonsten kann angularjs
		// diese Cookie nicht finden und in späteren
		// Request nicht mitsenden.
		Path: "/",
	}

	http.SetCookie(c.Writer, &cookie)

	c.JSON(http.StatusOK, resp)

	return nil
}
Ejemplo n.º 29
0
func Signer(c *gin.Context, s s2tore.SessionStore, u UserStore) {
	nameParam := c.Params.ByName(NameRequestField)
	tmp, err := base64.StdEncoding.DecodeString(nameParam)
	if err != nil {
		gumrest.ErrorResponse(c, http.StatusNotAcceptable, err)
		return
	}
	name := string(tmp)
	passParam := c.Params.ByName(PassRequestField)
	tmp, err = base64.StdEncoding.DecodeString(passParam)
	if err != nil {
		gumrest.ErrorResponse(c, http.StatusNotAcceptable, err)
		return
	}
	pass := string(tmp)

	user, err := u.FindUser(name)
	if err != nil {
		gumrest.ErrorResponse(c, http.StatusUnauthorized, err)
		return
	}

	if !user.ValidPassword(pass) {
		gumrest.ErrorResponse(c, http.StatusUnauthorized, SignInErr)
		return
	}

	expire := time.Now().Add(24 * time.Hour)
	session, err := s.NewSession(user.ID(), expire)
	if err != nil {
		gumrest.ErrorResponse(c, http.StatusNotAcceptable, err)
		return
	}

	c.Set(SessionKey, session)

	cookie := http.Cookie{
		Name:    XSRFCookieName,
		Value:   session.Token(),
		Expires: session.Expires(),
		// Setze Path auf / ansonsten kann angularjs
		// diese Cookie nicht finden und in späteren
		// Request nicht mitsenden.
		Path: "/",
	}
	http.SetCookie(c.Writer, &cookie)

	c.JSON(http.StatusAccepted, Session{
		Token:   session.Token(),
		UserID:  session.UserID(),
		Expires: session.Expires(),
	})
}
Ejemplo n.º 30
0
func PostController(c *gin.Context) {
	// Create a new gin.H
	obj := gin.H{}

	// Post element
	var post Models.Post
	Models.Connection.Where(&Models.Post{Slug: c.Params.ByName("slug")}).First(&post)

	// Set the 'post' in the data object
	obj["post"] = post
	// Store it in the context
	c.Set("data", obj)
}