Beispiel #1
0
func Callback(ctx context.Context) error {
	provider_type := ctx.PathValue("provider")
	provider, err := gomniauth.Provider(provider_type)
	if err != nil {
		log.Error("Error on getting provider: " + err.Error())
		return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."})
	}
	creds, err := provider.CompleteAuth(ctx.QueryParams())
	if err != nil {
		log.Error("Error on completing auth: " + err.Error())
		return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."})
	}
	// load the user
	// https://github.com/stretchr/gomniauth/blob/master/common/user.go
	user, userErr := provider.GetUser(creds)
	if userErr != nil {
		log.Error("Error on getting user: "******"An error has occured."})
	}

	passport := m.Passport{}
	err = m.GetDB("Passport").
		Find(bson.M{"provider": provider_type,
			"identifier": user.IDForProvider(provider_type)}).
		One(&passport)
	if err != nil {
		if err.Error() == "not found" {
			var currentUser, ok = ctx.Data()["user"].(m.User)
			if ok {
				err = m.GetDB("Passport").
					Insert(&m.Passport{bson.NewObjectId(), currentUser.Id, "", provider_type,
						user.IDForProvider(provider_type), fmt.Sprintf("%v", creds.Map.Get("access_token").Data()),
						fmt.Sprintf("%v", creds.Map.Get("refresh_token").Data())})
				if err != nil {
					log.Error("Error on registration with provider " + provider_type + ", new passport: " + err.Error())
					return goweb.API.Respond(ctx, 200, nil, []string{"Could not create your new authorization."})
				}
				log.Info("Connecting user")
				url, _ := url.Parse(utils.EnvUrl() + "/#/fblogin/?token=" + currentUser.Token)
				return goweb.Respond.WithRedirect(ctx, url)
			} else {
				// No user, create user, create passport
				var token = nonce.NewToken()
				nonce.MarkToken(token)
				newUser := m.User{bson.NewObjectId(), user.Nickname(), user.Email(), true, token, time.Now()}
				err = m.GetDB("User").Insert(&newUser)
				if err != nil {
					log.Error("Error on registration with provider " + provider_type + ", new user: "******"Failed to register."})
				}
				err = m.GetDB("Passport").
					Insert(&m.Passport{bson.NewObjectId(), newUser.Id, "", provider_type,
						user.IDForProvider(provider_type), fmt.Sprintf("%v", creds.Map.Get("access_token").Data()),
						fmt.Sprintf("%v", creds.Map.Get("refresh_token").Data())})
				if err != nil {
					log.Error("Error on registration with provider " + provider_type + ", new user passport: " + err.Error())
					return goweb.API.Respond(ctx, 200, nil, []string{"Failed to create your new passport."})
				}
				log.Info("New user registered")
				url, _ := url.Parse(utils.EnvUrl() + "/#/fblogin/?token=" + newUser.Token)
				return goweb.Respond.WithRedirect(ctx, url)
			}
		} else {
			log.Error("Error on registration with provider " + provider_type + ", new passport: " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"Could not find your authorization."})
		}
	} else {
		// login the user
		var user = m.User{}
		fmt.Println(passport)
		err = m.GetDB("User").Find(bson.M{"_id": passport.User}).One(&user)
		if err != nil {
			log.Error("Error on login with provider " + provider_type + ", user query: " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"Could not find you on the database."})
		}
		log.Info("Found user returning id")
		url, _ := url.Parse(utils.EnvUrl() + "/#/fblogin/?token=" + user.Token)
		return goweb.Respond.WithRedirect(ctx, url)
	}
}
Beispiel #2
0
func main() {

	log.Info("Glasgow Memories Server")
	log.Info("=======================")

	utils.InitEnv()
	var Address = ":" + utils.EnvPort()
	var baseURL = utils.EnvUrl()

	m.Connect()
	defer m.Close()

	// prepare the decryption key
	if utils.LoadCypherKey() != nil {
		log.Error("Failed to load the decryption key.")
		return
	}

	// GOMNIAUTH
	gomniauth.SetSecurityKey(signature.RandomKey(64))
	gomniauth.WithProviders(
		facebook.New("1497244403859030", "fbbb08c47e0441bcf23ea82b5f340fe5",
			baseURL+"/api/auth/facebook/callback/"),
	)

	// Attach the DB collection references to the context in order to pass it around
	goweb.MapBefore(func(ctx context.Context) error {
		var user = m.User{}
		cookieC, err := ctx.HttpRequest().Cookie("token")
		var cookie string
		if err != nil {
			cookie = ctx.FormValue("token")
			if cookie == "" {
				return nil
			}
		} else {
			cookie = cookieC.Value
		}
		err = m.GetDB("User").Find(bson.M{"token": cookie}).One(&user)
		if err != nil {
			// log.Info("MapBefore 2 " + err.Error())
			return nil
		}
		ctx.Data()["user"] = user
		return nil
	})

	goweb.MapStatic("/static", "../static")   // This is the directory with all static UI files
	goweb.MapStatic("/uploads", "../uploads") // This is the directory where we should store uploaded files

	// ENDPOINTS
	goweb.Map("GET", "/", endpoints.Root)
	goweb.Map("POST", "api/auth/local/register", endpoints.Register)
	goweb.Map("POST", "api/auth/local/login", endpoints.Login)
	goweb.Map("GET", "api/auth/{provider}/callback", endpoints.Callback)
	goweb.Map([]string{"GET", "POST"}, "api/auth/{provider}/{action}", endpoints.Connect)
	goweb.Map("POST", "api/upload/image", endpoints.UploadImage)
	goweb.Map("GET", "api/images/get", endpoints.GetImages)
	goweb.Map("POST", "api/upload/csv", endpoints.UploadTrail)
	goweb.Map("GET", "api/trails/get", endpoints.GetTrails)
	goweb.Map("POST", "api/upload/video", endpoints.UploadVideo)
	goweb.Map("GET", "api/videos/get", endpoints.GetVideos)
	goweb.Map("GET", "api/user", endpoints.GetUserInfo)
	goweb.Map("GET", "api/stats/get", endpoints.GetStats)
	goweb.Map("GET", "api/popLocations", endpoints.GetPopularLocations)
	goweb.Map("POST", "api/upload/imagetable", endpoints.UploadImageTable)
	goweb.Map("POST", "api/upload/zip", endpoints.UploadZip)
	// TODO: Add new endpoints here

	goweb.Map(endpoints.NotFound)

	// Remove the information from the data just in case the call is intercepted
	goweb.MapAfter(func(ctx context.Context) error {
		ctx.Data()["user"] = ""
		return nil
	})

	// setup the API responder
	codecService := services.NewWebCodecService()
	codecService.RemoveCodec("text/xml")
	apiResponder := responders.NewGowebAPIResponder(codecService, goweb.Respond)
	apiResponder.StandardFieldDataKey = "data"
	apiResponder.StandardFieldStatusKey = "status"
	apiResponder.StandardFieldErrorsKey = "errors"
	goweb.API = apiResponder

	// SERVER
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    5 * time.Minute,
		WriteTimeout:   5 * time.Minute,
		MaxHeaderBytes: 1 << 20,
	}
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)
	log.Info("Server port: " + Address)
	log.Info("Server running at: " + baseURL + "\n")
	if listenErr != nil {
		log.Error("Could not listen: " + listenErr.Error())
	}

	go func() {
		for _ = range c {
			// sig is a ^C, handle it
			// stop the HTTP server
			log.Info("Stopping the server...\n")
			listener.Close()
			log.Info("Server stopped.\n")
		}
	}()
	// begin the server
	log.Error("Error in Serve: " + s.Serve(listener).Error())
}