Пример #1
0
Файл: jwt.go Проект: ajoulie/goa
// ContextJWT retrieves the JWT token from a `context` that went through our security
// middleware.
func ContextJWT(ctx context.Context) *jwt.Token {
	token, ok := ctx.Value(jwtKey).(*jwt.Token)
	if !ok {
		return nil
	}
	return token
}
Пример #2
0
/*
Path returns the path that the Goji router uses to perform the PathPrefix
optimization. While this function does not distinguish between the absence of a
path and an empty path, Goji will automatically extract a path from the request
if none is present.

By convention, paths are stored in their escaped form (i.e., the value returned
by net/url.URL.EscapedPath, and not URL.Path) to ensure that Patterns have as
much discretion as possible (e.g., to behave differently for '/' and '%2f').
*/
func Path(ctx context.Context) string {
	pi := ctx.Value(internal.Path)
	if pi == nil {
		return ""
	}
	return pi.(string)
}
Пример #3
0
func appUserToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// get t from ctx
	t := ctx.Value("test").(*testing.T)

	// Test whether the user is authenticated
	if r.Header.Get("X-Identity-Status") != "Confirmed" {
		t.Errorf("At the app, the user token should already be confirmed, got: %v", r.Header.Get("X-Identity-Status"))
	}
	if r.Header.Get("X-User-Id") != "10a2e6e717a245d9acad3e5f97aeca3d" {
		t.Errorf("At the app, the user should be 10a2e6e717a245d9acad3e5f97aeca3d, got: %v", r.Header.Get("X-User-Id"))
	}
	if r.Header.Get("X-User-Name") != "testuser" {
		t.Errorf("At the app, the user should be testuser, got: %v", r.Header.Get("X-User-Name"))
	}
	if r.Header.Get("X-Domain-Id") != "default" {
		t.Errorf("At the app, the user should be default, got: %v", r.Header.Get("X-Domain-Id"))
	}

	// Test ctx's Context Parameter with key "UserAccessInfo"
	value := router.MiddlewareParam(ctx, UserAccessInfoKey)
	if value == nil {
		t.Error("ctx should contain user access info")
	} else {
		access, ok := value.(*client.AccessInfo)
		if !ok {
			t.Error("it is not accessinfo, what is it?")
		}
		if access.Token != "usertoken" || access.TokenInfo.User.Domain.Name != "Default" {
			t.Error("ctx's accessinfo contains wrong information")
		}
	}

	w.Write([]byte("Test success!"))
}
Пример #4
0
func deleteNote(ctx context.Context, req interface{}) (interface{}, *ErrorResponse) {
	db := ctx.Value("db").(*gorp.DbMap)
	noteId, err := strconv.Atoi(kami.Param(ctx, "noteId"))

	if err != nil {
		return nil, &ErrorResponse{
			http.StatusBadRequest,
			fmt.Sprintf("Invalid note id format: %v", err),
		}
	}

	note := new(model.Note)
	err = db.SelectOne(note, "select * from notes where id = ?", noteId)
	if err != nil {
		return nil, &ErrorResponse{
			http.StatusBadRequest,
			fmt.Sprintf("Query failed: %v", err),
		}
	}

	if _, err := db.Delete(note); err != nil {
		return nil, &ErrorResponse{
			http.StatusInternalServerError,
			fmt.Sprintf("Delete failed: %v", err),
		}
	}

	return nil, nil
}
Пример #5
0
// EffectiveCallerIDFromContext returns the EffectiveCallerID(vtpb.CallerID)
// stored in the Context, if any
func EffectiveCallerIDFromContext(ctx context.Context) *vtpb.CallerID {
	ef, ok := ctx.Value(effectiveCallerIDKey).(*vtpb.CallerID)
	if ok && ef != nil {
		return ef
	}
	return nil
}
Пример #6
0
func register(ctx context.Context, req interface{}) (interface{}, *ErrorResponse) {
	input := req.(*registerRequest)
	dbMap := ctx.Value("db").(*gorp.DbMap)

	if input.Username == "" {
		return nil, &ErrorResponse{http.StatusBadRequest, "username is empty"}
	}

	if input.Password == "" {
		return nil, &ErrorResponse{http.StatusBadRequest, "password is empty"}
	}

	count, err := dbMap.SelectInt("select count(id) from users where username = ?", input.Username)
	if err != nil {
		return nil, &ErrorResponse{http.StatusInternalServerError, err.Error()}
	}
	if count > 0 {
		return nil, &ErrorResponse{http.StatusBadRequest, "user exists"}
	}

	user := model.User{
		0,
		input.Username,
		auth.HashPassword(input.Username, input.Password),
		input.Email,
		time.Now().UnixNano(),
		time.Now().UnixNano(),
	}

	if err := dbMap.Insert(&user); err != nil {
		return nil, &ErrorResponse{http.StatusInternalServerError, err.Error()}
	}

	return map[string]string{"message": "user created"}, nil
}
Пример #7
0
// Load will return the current session, creating one if necessary. This will
// fail if a store wasn't installed with HandlerWithStore somewhere up the
// call chain.
func Load(ctx context.Context, namespace string) (*Session, error) {
	rc, ok := ctx.Value(reqCtxKey).(*reqCtx)
	if !ok {
		return nil, errors.ProgrammerError.New(
			"no session store handler wrapper installed")
	}
	if rc.cache != nil {
		if session, exists := rc.cache[namespace]; exists {
			return session, nil
		}
	}
	sessiondata, err := rc.s.Load(rc.r, namespace)
	if err != nil {
		return nil, err
	}
	session := &Session{
		SessionData: sessiondata,
		store:       rc.s,
		namespace:   namespace}
	if rc.cache == nil {
		rc.cache = map[string]*Session{namespace: session}
	} else {
		rc.cache[namespace] = session
	}
	return session, nil
}
Пример #8
0
// FromContext returns authentication information from the context or
// nil if no such information present.
func FromContext(ctx context.Context) *Info {
	info, ok := ctx.Value(infoKey).(*Info)
	if !ok {
		return nil
	}
	return info
}
Пример #9
0
// SpanFromContext returns the `Span` previously associated with `ctx`, or
// `nil` if no such `Span` could be found.
//
// NOTE: context.Context != SpanContext: the former is Go's intra-process
// context propagation mechanism, and the latter houses OpenTracing's per-Span
// identity and baggage information.
func SpanFromContext(ctx context.Context) Span {
	val := ctx.Value(activeSpanKey)
	if sp, ok := val.(Span); ok {
		return sp
	}
	return nil
}
Пример #10
0
func Parse(ctx context.Context) (*CommandArgument, error) {
	var (
		err        error
		commandArg *CommandArgument
		catVar     = ctx.Value("cat").(cat.Cat)
		imagePath  = ctx.Value("imagepath").(string)
	)

	params, ok := generalArgPattern.FindStringSubmatchMap(imagePath)
	if ok {
		commandArg, err = makeGeneralArg(imagePath, params)
	} else {
		params, ok = sourceDigitalMarkArgPattern.FindStringSubmatchMap(imagePath)
		if ok {
			commandArg.digitalMarkOnSource = true
			commandArg, err = makeDigitalMarkOnSourceArg(params)
		} else {
			err = errors.New("Image.Command.ParseError")
			log.WithFields(log.Fields{"uri": imagePath}).Warn(err.Error())
			util.LogErrorEvent(catVar, "URI.ParseError", "")
		}
	}

	return commandArg, err
}
Пример #11
0
//ReadTokenManagerFromContext returns tokenManager from context.
// Must have been set by ContextWithTokenManager ONLY
func ReadTokenManagerFromContext(ctx context.Context) token.Manager {
	tm := ctx.Value(contextTokenManagerKey)
	if tm != nil {
		return tm.(token.Manager)
	}
	return nil
}
Пример #12
0
// CurrentSpan returns the Span value for the provided Context
func CurrentSpan(ctx context.Context) *Span {
	if span := ctx.Value(contextKeyTracing); span != nil {
		return span.(*Span)
	}

	return nil
}
Пример #13
0
// groupFromContext returns the Group from the ctx.
func groupFromContext(ctx context.Context) (*Group, error) {
	group, ok := ctx.Value(groupKey).(*Group)
	if !ok {
		return nil, errNoGroupFromContext
	}
	return group, nil
}
Пример #14
0
// specFromContext returns the Spec from the ctx.
func specFromContext(ctx context.Context) (*Spec, error) {
	spec, ok := ctx.Value(specKey).(*Spec)
	if !ok {
		return nil, errNoSpecFromContext
	}
	return spec, nil
}
Пример #15
0
// contextPairs takes a slice of string keys, obtains their values from the
// context.Context and returns the suitable list of key value pairs as a
// []interface{}.
func contextPairs(ctx context.Context, keys ...string) []interface{} {
	var pairs []interface{}
	for _, k := range keys {
		pairs = append(pairs, k, ctx.Value(k))
	}
	return pairs
}
Пример #16
0
func TokenFromContext(ctx context.Context) (*jwt.Token, error) {
	args, ok := ctx.Value(authKey).(*authorization)
	if !ok {
		return nil, errors.Errorf("Could not assert type for %v", ctx.Value(authKey))
	}
	return args.token, nil
}
Пример #17
0
func Logf(ctx netcontext.Context, level int64, format string, args ...interface{}) {
	if f, ok := ctx.Value(&logOverrideKey).(logOverrideFunc); ok {
		f(level, format, args...)
		return
	}
	logf(fromContext(ctx), level, format, args...)
}
Пример #18
0
func SubjectFromContext(ctx context.Context) (string, error) {
	args, ok := ctx.Value(authKey).(*authorization)
	if !ok {
		return "", errors.Errorf("Could not assert type for %v", ctx.Value(authKey))
	}
	return args.claims.GetSubject(), nil
}
Пример #19
0
// UserFromContext returns the Twitter User from the ctx.
func UserFromContext(ctx context.Context) (*twitter.User, error) {
	user, ok := ctx.Value(userKey).(*twitter.User)
	if !ok {
		return nil, fmt.Errorf("twitter: Context missing Twitter User")
	}
	return user, nil
}
Пример #20
0
// MustFromContext extracts the identity from ctx.
// If not present it panics.
func MustFromContext(ctx context.Context) *Identity {
	idt, ok := ctx.Value(idtKey).(*Identity)
	if !ok {
		panic("identity is not registered")
	}
	return idt
}
Пример #21
0
func updateNote(ctx context.Context, req interface{}) (interface{}, *ErrorResponse) {
	db := ctx.Value("db").(*gorp.DbMap)
	newNote := req.(*model.Note)
	noteId, err := strconv.Atoi(kami.Param(ctx, "noteId"))

	if err != nil {
		return nil, &ErrorResponse{
			http.StatusBadRequest,
			fmt.Sprintf("Invalid note id format: %v", err),
		}
	}

	note := new(model.Note)
	err = db.SelectOne(note, "select * from notes where id = ?", noteId)
	if err != nil {
		return nil, &ErrorResponse{
			http.StatusBadRequest,
			fmt.Sprintf("Query failed: %v", err),
		}
	}

	note.Title = newNote.Title
	note.Content = newNote.Content
	note.OwnerId = newNote.OwnerId
	note.UpdatedAt = time.Now().UnixNano()

	if _, err := db.Update(note); err != nil {
		return nil, &ErrorResponse{
			http.StatusInternalServerError,
			fmt.Sprintf("Update failed: %v", err),
		}
	}

	return note, nil
}
Пример #22
0
func MustFromTokenContext(ctx context.Context) string {
	t, ok := ctx.Value(tokenKey).(string)
	if !ok {
		panic("token is not registered")
	}
	return t
}
Пример #23
0
// ImmediateCallerIDFromContext returns the ImmediateCallerID(querypb.VTGateCallerID)
// stored in the Context, if any
func ImmediateCallerIDFromContext(ctx context.Context) *querypb.VTGateCallerID {
	im, ok := ctx.Value(immediateCallerIDKey).(*querypb.VTGateCallerID)
	if ok && im != nil {
		return im
	}
	return nil
}
Пример #24
0
func Message(c context.Context) string {
	m, ok := c.Value(MessageKey).(string)
	if ok {
		return m
	}
	return ""
}
Пример #25
0
func statusFrom(ctx context.Context) statusType {
	s, ok := ctx.Value(statusKey).(statusType)
	if !ok {
		panic("missing status in context")
	}
	return s
}
Пример #26
0
func getHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	gun := vars["imageName"]
	checksum := vars["checksum"]
	tufRole := vars["tufRole"]
	s := ctx.Value("metaStore")

	store, ok := s.(storage.MetaStore)
	if !ok {
		return errors.ErrNoStorage.WithDetail(nil)
	}

	lastModified, output, err := getRole(ctx, store, gun, tufRole, checksum)
	if err != nil {
		return err
	}
	if lastModified != nil {
		// This shouldn't always be true, but in case it is nil, and the last modified headers
		// are not set, the cache control handler should set the last modified date to the beginning
		// of time.
		utils.SetLastModifiedHeader(w.Header(), *lastModified)
	} else {
		logrus.Warnf("Got bytes out for %s's %s (checksum: %s), but missing lastModified date",
			gun, tufRole, checksum)
	}

	w.Write(output)
	return nil
}
Пример #27
0
func (m *MockHandlerContextRead) ServeHTTP(rw http.ResponseWriter, r *http.Request, ctx context.Context, n interfaces.HandlerFunc) {
	ctxValue, ok := ctx.Value("testKey").(string)
	if ok {
		rw.Write([]byte(ctxValue))
	}
	n(rw, r, ctx)
}
Пример #28
0
// FromContext retreives the request's xstats client from a given context if any.
// If no xstats is embeded in the context, a nop instance is returned so you can
// use it safely without having to test for it's presence.
func FromContext(ctx context.Context) XStater {
	rc, ok := ctx.Value(xstatsKey).(XStater)
	if ok {
		return rc
	}
	return nop
}
Пример #29
0
func getCurFilters(c context.Context) []RawFilter {
	curFiltsI := c.Value(taskQueueFilterKey)
	if curFiltsI != nil {
		return curFiltsI.([]RawFilter)
	}
	return nil
}
Пример #30
0
// ContextRequestID extracts the Request ID from the context.
func ContextRequestID(ctx context.Context) (reqID string) {
	id := ctx.Value(reqIDKey)
	if id != nil {
		reqID = id.(string)
	}
	return
}