Exemple #1
0
func (rc *ResourceController) GetResources(ctx *gin.Context) {
	req := ctx.Request
	resourceType := getResourceType(req.URL)

	logger.Log.WithFields(
		logrus.Fields{"resource type": resourceType}).Info("GetResources")

	resources := ptm_models.NewSliceForResourceName(resourceType, 0, 0)
	c := rc.Database().C(ptm_models.GetCollectionName(resourceType))
	// retrieve all documents in the collection
	// TODO Restrict this to resource type, just to be extra safe
	query := buildSearchQuery(resourceType, ctx)
	logger.Log.WithFields(
		logrus.Fields{"query": query}).Info("GetResources")
	err := c.Find(query).All(resources)
	if err != nil {
		if err == mgo.ErrNotFound {
			ctx.String(http.StatusNotFound, "Not Found")
			ctx.Abort()
			return
		} else {
			ctx.AbortWithError(http.StatusBadRequest, err)
			return
		}
	}

	ctx.JSON(http.StatusOK, resources)
}
Exemple #2
0
// UserDelete removes a specific user.
func UserDelete(c *gin.Context) {
	record := session.User(c)

	err := store.DeleteUser(
		c,
		record,
	)

	if err != nil {
		logrus.Warnf("Failed to delete user. %s", err)

		c.JSON(
			http.StatusBadRequest,
			gin.H{
				"status":  http.StatusBadRequest,
				"message": "Failed to delete user",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		gin.H{
			"status":  http.StatusOK,
			"message": "Successfully deleted user",
		},
	)
}
Exemple #3
0
// AuthRefresh represents the refresh handler.
func AuthRefresh(c *gin.Context) {
	record := session.Current(c)

	token := token.New(token.SessToken, record.Username)
	result, err := token.SignExpiring(record.Hash, config.Session.Expire)

	if err != nil {
		logrus.Warnf("Failed to refresh token. %s", err)

		c.JSON(
			http.StatusUnauthorized,
			gin.H{
				"status":  http.StatusUnauthorized,
				"message": "Failed to refresh token",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		result,
	)
}
Exemple #4
0
// OrgTeamIndex retrieves all teams related to a org.
func OrgTeamIndex(c *gin.Context) {
	records, err := store.GetOrgTeams(
		c,
		&model.OrgTeamParams{
			Org: c.Param("org"),
		},
	)

	if err != nil {
		logrus.Warnf("Failed to fetch org teams. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to fetch teams",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		records,
	)
}
Exemple #5
0
// ProfileToken displays the users token.
func ProfileToken(c *gin.Context) {
	record := session.Current(c)

	token := token.New(token.UserToken, record.Username)
	result, err := token.SignUnlimited(record.Hash)

	if err != nil {
		logrus.Warnf("Failed to generate token. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to generate token",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		result,
	)
}
Exemple #6
0
// TeamUserIndex retrieves all users related to a team.
func TeamUserIndex(c *gin.Context) {
	records, err := store.GetTeamUsers(
		c,
		&model.TeamUserParams{
			Team: c.Param("team"),
		},
	)

	if err != nil {
		logrus.Warnf("Failed to fetch team users. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to fetch users",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		records,
	)
}
Exemple #7
0
// UserIndex retrieves all available users.
func UserIndex(c *gin.Context) {
	records, err := store.GetUsers(
		c,
	)

	if err != nil {
		logrus.Warnf("Failed to fetch users. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to fetch users",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		records,
	)
}
Exemple #8
0
// UserOrgIndex retrieves all orgs related to a user.
func UserOrgIndex(c *gin.Context) {
	records, err := store.GetUserOrgs(
		c,
		&model.UserOrgParams{
			User: c.Param("user"),
		},
	)

	if err != nil {
		logrus.Warnf("Failed to fetch user orgs. %s", err)

		c.JSON(
			http.StatusInternalServerError,
			gin.H{
				"status":  http.StatusInternalServerError,
				"message": "Failed to fetch orgs",
			},
		)

		c.Abort()
		return
	}

	c.JSON(
		http.StatusOK,
		records,
	)
}
Exemple #9
0
func (p *policy) checkSSL(c *gin.Context) bool {
	if !p.config.SSLRedirect {
		return true
	}

	req := c.Request
	isSSLRequest := strings.EqualFold(req.URL.Scheme, "https") || req.TLS != nil
	if isSSLRequest {
		return true
	}

	// TODO
	// req.Host vs req.URL.Host
	url := req.URL
	url.Scheme = "https"
	url.Host = req.Host

	if len(p.config.SSLHost) > 0 {
		url.Host = p.config.SSLHost
	}

	status := http.StatusMovedPermanently
	if p.config.SSLTemporaryRedirect {
		status = http.StatusTemporaryRedirect
	}
	c.Redirect(status, url.String())
	c.Abort()
	return false
}
Exemple #10
0
func (rc *ResourceController) GetResource(ctx *gin.Context) {
	var id bson.ObjectId
	req := ctx.Request
	resourceType := getResourceType(req.URL)

	// Validate id as a bson Object ID
	id, err := toBsonObjectID(ctx.Param("id"))
	if err != nil {
		ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	logger.Log.WithFields(
		logrus.Fields{"resource type": resourceType, "id": id}).Info("GetResource")

	resource, err := rc.LoadResource(resourceType, id)
	if err != nil {
		if err == mgo.ErrNotFound {
			ctx.String(http.StatusNotFound, "Not Found")
			ctx.Abort()
			return
		} else {
			ctx.AbortWithError(http.StatusBadRequest, err)
			return
		}
	}

	logger.Log.WithFields(logrus.Fields{"resource": resource}).Info("GetResource")

	ctx.JSON(http.StatusOK, resource)
}
Exemple #11
0
func (w *Whitelist) Handler(c *gin.Context) {
	if w.interval > 0 {
		w.mutex.RLock()
		defer w.mutex.RUnlock()
	}

	if len(w.cidrs) == 0 {
		return
	}

	remoteip := remoteIP(c)
	if len(remoteip) == 0 {
		return
	}

	netip := net.ParseIP(remoteip)
	if netip == nil {
		return
	}

	for _, cidr := range w.cidrs {
		if cidr.Contains(netip) {
			return
		}
	}

	c.String(http.StatusInternalServerError, "Bad Host")
	c.Abort()
}
Exemple #12
0
func RestError(c *gin.Context, err interface{}) error {
	restError := BuildError(err)

	c.JSON(restError.Code, models.JSON{"error": restError.Message})
	c.Abort()

	return errors.New(restError.String())
}
Exemple #13
0
func (this PlayersController) Authenticate(ginContext *gin.Context) {
	_, err := models.Player{}.Find(this.Context.AeContext, this.Context.AccessToken)

	if err.Any() {
		this.RespondWith.Error(http.StatusForbidden, api.UserError("Invalid Access Token"))
		ginContext.Abort()
	}
}
//Middleware for restricting input content
func RestrictInputContent(c *gin.Context) {
	fmt.Println(c.Request.ContentLength)
	if c.Request.ContentLength > myConstants.MaxInputContentLength {
		c.JSON(http.StatusRequestEntityTooLarge, gin.H{"eror": true, "message": myMessages.ContentTooLarge})
		c.Abort()
		return
	}
}
Exemple #15
0
func respondWithError(code int, message string, c *gin.Context) {
	resp := map[string]string{"error": message}
	if code == http.StatusForbidden {
		go GlobalSessions.SessionDestroy(c.Writer, c.Request)
	}
	c.JSON(code, resp)
	c.Abort()
}
Exemple #16
0
func LoginUnauthenticated(ctx *gin.Context) {

	ctx.String(401, "You are not logged in!")

	// ctx.Abort() means no other handlers will be ran after this one, meaning the route controller won't execute
	ctx.Abort(-1)

}
Exemple #17
0
func InitUserCheck(c *gin.Context) {
	memConfMux.RLock()
	userCount := len(memConfUsers)
	memConfMux.RUnlock()

	if userCount == 0 {
		Error(c, USER_NOT_INIT)
		c.Abort()
	}
}
Exemple #18
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()
}
Exemple #19
0
func SystemAdminCheck(c *gin.Context) {
	if token := c.Request.Header.Get(XAuthToken); token == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
		c.Abort()
		return
	}

	//TODO : System User Check

	c.Next()
}
Exemple #20
0
// unauthorizedRequest sends back a failure to the client
func (r KubeCover) unauthorizedRequest(cx *gin.Context, spec, message string) {
	glog.Errorf("unauthorized request from: (%s), failure: %s violation", cx.Request.RemoteAddr, message)
	glog.Errorf("failing specification: %s", spec)

	// step: inject the header
	cx.JSON(http.StatusNotAcceptable, gin.H{
		"status":  "Failure",
		"message": "security policy violation, reason: " + message,
	})
	cx.Abort()
}
Exemple #21
0
// AbortUnauthorized stops the middleware execution with JSON error.
func AbortUnauthorized(c *gin.Context) {
	c.JSON(
		http.StatusForbidden,
		gin.H{
			"status":  http.StatusForbidden,
			"message": "You are not authorized to request this resource",
		},
	)

	c.Abort()
}
Exemple #22
0
func AuthFailed(c *gin.Context) {
	if isXHR(c) == false {
		c.Redirect(302, "/?hai")
	} else {
		c.Writer.WriteHeader(401)
	}

	c.Abort()

	return
}
Exemple #23
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()
}
Exemple #24
0
func UpdateDeveloper(c *gin.Context) {
	changes := &m.Developer{Name: c.PostForm("name"), GithubAccount: c.PostForm("github")}
	dev := &m.Developer{}
	dev.LoggedUser(&db, c)
	err := dev.Update(&db, changes)
	if err != nil {
		c.Error(err)
	} else {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
	}
}
Exemple #25
0
func (auth *UserAuthenticator) BasicAuthForUser(c *gin.Context) bool {
	u, p, _ := c.Request.BasicAuth()
	if auth.AuthenticateUser(u, p) {
		return true
	}

	c.Header("WWW-Authenticate", "Basic realm=\"Status Dashboard\"")
	c.String(http.StatusUnauthorized, "Login required.")
	c.Abort()

	return false
}
Exemple #26
0
func GetIdParam(param string, c *gin.Context) uuid.UUID {
	id, err := uuid.FromString(param)
	if err != nil {
		errorResponse := ErrorResponse{
			Errors: []*Error{NewError(ErrCodeValueRequired, fmt.Sprintf("valid id required", param))},
		}
		c.JSON(http.StatusBadRequest, errorResponse)
		c.Abort()
		return uuid.Nil
	}

	return id
}
Exemple #27
0
func (mw *GinJWTMiddleware) unauthorized(c *gin.Context, code int, message string) {

	if mw.Realm == "" {
		mw.Realm = "gin jwt"
	}

	c.Header("WWW-Authenticate", "JWT realm="+mw.Realm)
	c.Abort()

	mw.Unauthorized(c, code, message)

	return
}
Exemple #28
0
func requiresConformance(c *gin.Context) {
	host := fmt.Sprintf("%s://%s", scheme(c.Request), c.Request.Host)
	correctXRequestedBy := c.Request.Header.Get("X-Requested-By") == "SpaceApi"
	// WARNING The Origin header attribute sometimes is not sent; we should not block these requests
	sameOriginPolicy := c.Request.Header.Get("Origin") == "" || host == c.Request.Header.Get("Origin")
	if correctXRequestedBy && sameOriginPolicy {
		c.Next()
	} else {
		c.JSON(http.StatusBadRequest, utils.H{
			"error": "missing X-Requested-By header attribute or Origin header does not comply with the same-origin policy",
		})
		c.Abort()
	}
}
func rateLimit(c *gin.Context) {

	ip := c.ClientIP()
	value := int(ips.Add(ip, 1))
	if value%50 == 0 {
		fmt.Printf("ip: %s, count: %d\n", ip, value)
	}
	if value >= 200 {
		if value%200 == 0 {
			fmt.Println("ip blocked")
		}
		c.Abort()
		c.String(503, "you were automatically banned :)")
	}
}
Exemple #30
0
func (l *Login) PostLogin(c *gin.Context) {
	valid, _ := l.AuthEngine.ValidateAndSetCookie(ginAuth.AuthenticationCredentials{
		Username: c.PostForm("username"),
		Password: c.PostForm("password"),
	}, c)
	if valid {
		c.Redirect(http.StatusSeeOther, "/")
		c.Abort()
	} else {
		c.HTML(http.StatusUnauthorized, "login.tpl", gin.H{
			"title": "Login",
			"error": "wrong username or password " + strconv.FormatBool(valid),
		})
	}
}