Exemple #1
0
//
// Middleware called every call that requires user Authentication
// It injects the Auth object in handlers that require it to work
// Return the user in this context or an anonymous user and an error
// Should be used .Logged to identify if it's an anonymous user
// and use .GetUser to get this context user or the anonymous user the error object
//
func AuthMiddleware(c martini.Context, db DB, r render.Render, req *http.Request) {
	anonymous := &User{
		UserId:     "anonymous",
		UserName:   "******",
		PicId:      "default",
		FullName:   "Usuario Anonimo",
		LikeCount:  0,
		Creation:   time.Now(),
		LastUpdate: time.Now(),
		Deleted:    false,
		Admin:      false,
	}

	// Try to get the credentials from Authorization header or credentials cookie
	credentials := req.Header.Get("Authorization")
	if credentials == "" {
		cookie, err := req.Cookie("credentials")
		if err == nil {
			credentials = cookie.Value
		}
	}

	if credentials == "" {
		err := errors.New("Voce nao apresentou credenciais de autorizacao")
		userAuth := &UserAuth{anonymous, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Handler aborted
			// If the nex handler aborted, by an empty return
			// So he can't go on without user, let's alert user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	// Len of our 41 (20:20) char encoded in base64 is 56
	// (C++) long base64EncodedSize = 4 * (int)Math.Ceiling(originalSizeInBytes / 3.0);
	if len(credentials) != 56 {
		err := errors.New("Credenciais de authorizacao apresentadas sao invalidas.")
		userAuth := &UserAuth{anonymous, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Handler aborted
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	token, err := decodeAuth(credentials)
	if err != nil {
		userAuth := &UserAuth{anonymous, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Handler aborted
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	obj, err := db.Get(Token{}, token.TokenId, token.UserId)
	if err != nil {
		userAuth := &UserAuth{anonymous, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Handler aborted
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	if obj == nil {
		// This tokenid was not found
		err = errors.New("Credenciais fornecidas nao foram encontradas")
		userAuth := &UserAuth{anonymous, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Handler aborted
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	token = obj.(*Token)

	obj, err = db.Get(User{}, token.UserId)
	if err != nil {
		userAuth := &UserAuth{anonymous, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Handler aborted
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	user := obj.(*User)
	userAuth := &UserAuth{user: user, err: nil}
	// Here the next handler has got the user
	c.MapTo(userAuth, (*Auth)(nil))
}
Exemple #2
0
func AuthMiddleware(c martini.Context, db DB, r render.Render, req *http.Request) {
	header := req.Header.Get("Authorization")
	if header == "" {
		err := errors.New("Voce nao apresentou credenciais de autorizacao")
		userAuth := &UserAuth{nil, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next() // Call the next handler
		if !c.Written() {
			// If the nex handler aborted, empty return
			// So he can't go on without user, let's alert user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	// Len of our 41 (20:20) char encoded in base64 is 56
	// (C++) long base64EncodedSize = 4 * (int)Math.Ceiling(originalSizeInBytes / 3.0);
	if len(header) < 56 {
		err := errors.New("Credenciais de authorizacao apresentadas sao invalidas.")
		userAuth := &UserAuth{nil, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Response the user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	auth, err := decodeAuth(header)
	if err != nil {
		userAuth := &UserAuth{nil, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Response the user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	i := strings.Index(auth, ":")
	if i == -1 {
		err = errors.New("Credenciais de authorizacao estao corrompidas")
		userAuth := &UserAuth{nil, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Response the user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	tokenid := auth[:i]
	userid := auth[i+1:]

	obj, err := db.Get(Token{}, tokenid)
	if err != nil {
		userAuth := &UserAuth{nil, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Response the user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	if obj == nil {
		// This tokenid was not found
		err = errors.New("Credenciais fornecidas nao foram encontradas")
		userAuth := &UserAuth{nil, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Response the user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	token := obj.(*Token)
	if token.UserId != userid {
		err = errors.New("Usuario nao identificado pelas credenciais fornecidas")
		userAuth := &UserAuth{nil, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Response the user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	obj, err = db.Get(User{}, userid)
	if err != nil {
		userAuth := &UserAuth{nil, err}
		c.MapTo(userAuth, (*Auth)(nil))
		c.Next()          // Call the next handler
		if !c.Written() { // Response the user
			AccessDeniedHandler(r, req, err)
		}
		return
	}

	user := obj.(*User)
	userAuth := &UserAuth{user: user, err: nil}
	// Here the next handler has got the user
	c.MapTo(userAuth, (*Auth)(nil))
}