Beispiel #1
0
        public void Find_SearchByUserAndServiceType_ItemCreated()
        {
            var user = UserFaker.Create();

            var accessToken = ServiceAccessTokenRepository.FindOrUpdateAccessToken(user, Rand.RandomString(), ServiceType.GitHub);

            Assert.NotNull(accessToken);
        }
        public GitlabAuthController()
        {
            var clientId = AppConfig.GetConfiguration("auth:external:gitlab:client_id");

            var redirectUri = AppConfig.GetConfiguration("auth:external:gitlab:redirect_url");

            Get("/api/v1/auth/gitlab/login_link/get", _ => {
                var loginLink =
                    $"https://gitlab.com/oauth/authorize?client_id={clientId}&redirect_uri={redirectUri}" +
                    $"&response_type=token&scope={Scopes}";
                return(HttpResponse.Data(new JObject()
                {
                    ["login_link"] = loginLink
                }));
            });

            Get("/api/v1/auth/gitlab/get_auth_token", av => {
                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ShouldHaveParameters(new[] { "access_token" }),
                });
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                var accessToken = GetRequestStr("access_token");

                var client = new GitLabClient(accessToken);
                client.SetAuthorizedUser();

                if (client.User == null)
                {
                    return(HttpResponse.Error(HttpStatusCode.Unauthorized,
                                              "We're unable to get your access token, please try again"));
                }

                var user = UserRepository.FindByEmail(client.User.Email) ??
                           UserRepository.FindOrCreateByEmailAndLogin(
                    client.User.Email,
                    client.User.Login,
                    null,
                    UserRepository.FindByGuid(GetRequestStr("referral_key"))
                    );

                ServiceAccessTokenRepository.FindOrUpdateAccessToken(user, accessToken, ServiceType.GitLab);

                return(HttpResponse.Data(new JObject()
                {
                    ["token"] = Jwt.FromUserId(user.id)
                }));
            });
        }
        public FacebookAuthController()
        {
            Get("/api/v1/auth/facebook/my_token/get", _ => {
                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ShouldHaveParameters(new[] { "facebook_token" }),
                });
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                var facebookToken = GetRequestStr("facebook_token");

                var response = new HttpClient().GetAsync(
                    ApiUrl + $"me?access_token={facebookToken}&fields=name,email"
                    ).Result;
                if (!response.IsSuccessStatusCode)
                {
                    return(HttpResponse.Error(HttpStatusCode.BadRequest, "Invalid facebook token"));
                }

                var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);

                var email = json.Value <string>("email");
                var login = email.Split("@")[0];

                var user = UserRepository.FindByEmail(email) ??
                           UserRepository.FindOrCreateByEmailAndLogin(
                    email, login, null,
                    UserRepository.FindByGuid(GetRequestStr("referral_key"))
                    );

                var accessToken =
                    ServiceAccessTokenRepository.FindOrUpdateAccessToken(user, facebookToken, ServiceType.Facebook);
                accessToken.UpdateCol("origin_user_id", json.Value <string>("id"));

                return(HttpResponse.Data(new JObject()
                {
                    ["token"] = Jwt.FromUserId(user.id)
                }));
            });
        }
        public GithubAuthController()
        {
            var clientId     = AppConfig.GetConfiguration("auth:external:github:client_id");
            var clientSecret = AppConfig.GetConfiguration("auth:external:github:client_secret");

            Get("/api/v1/auth/github/login_link/get", _ => {
                var loginLink = $"https://github.com/login/oauth/authorize?scope={Scopes}&client_id={clientId}";
                return(HttpResponse.Data(new JObject()
                {
                    ["login_link"] = loginLink
                }));
            });

            Get("/api/v1/auth/github/get_auth_token", _ => {
                var responseBody = "";
                var code         = GetRequestStr("code");

                using (var client = new HttpClient()) {
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    var response = client.PostAsync(
                        "https://github.com/login/oauth/access_token",
                        new FormUrlEncodedContent(new[] {
                        new KeyValuePair <string, string>("client_id", clientId),
                        new KeyValuePair <string, string>("client_secret", clientSecret),
                        new KeyValuePair <string, string>("code", code),
                    })
                        ).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        responseBody = response.Content.ReadAsStringAsync().Result;
                    }
                }

                var json        = JObject.Parse(responseBody);
                var accessToken = json.Value <string>("access_token");

                if (accessToken == null)
                {
                    return(HttpResponse.Error(HttpStatusCode.Unauthorized,
                                              "We're unable to get your access token, please try again"));
                }

                var githubClient = new GitHubClient(new ProductHeaderValue("GitCom"));

                githubClient.Credentials = new Credentials(accessToken);

                var githubUser = githubClient.User.Current().Result;

                var userEmail = githubUser.Email ?? $"{Rand.RandomString()}[email protected]";

                var user = UserRepository.FindByEmail(userEmail) ??
                           UserRepository.FindOrCreateByEmailAndLogin(
                    userEmail, githubUser.Login, null,
                    UserRepository.FindByGuid(GetRequestStr("referral_key"))
                    );

                var tokenModel =
                    ServiceAccessTokenRepository.FindOrUpdateAccessToken(user, accessToken, ServiceType.GitHub);
                tokenModel.UpdateCol("origin_user_id", githubUser.Id.ToString());

                return(HttpResponse.Data(new JObject()
                {
                    ["token"] = Jwt.FromUserId(user.id)
                }));
            });
        }