public async Task SendReports()
        {
            var currentDay      = DateTime.Now;
            var currentDayInSec = new DateTimeOffset(currentDay).ToUnixTimeSeconds();

            if (currentDayInSec >= firstOfMonth)
            {
                var users = userPreferences.GetUniqueUsers();
                foreach (UserTeam ut in users)
                {
                    var monthData = userRecordService.RetrieveRawStats(ut.userID, ut.teamID);
                    if (!monthData.Error)
                    {
                        monthlyDataRepository.StoreData(ut.userID, ut.teamID, monthData.Stats);
                    }
                }
                var subscribers = subscriberRepository.GetSubscribers();
                if (subscribers.Any())
                {
                    foreach (UserTeam ut in subscribers)
                    {
                        var             report   = userRecordService.RetrieveMonthStats(ut.userID, ut.teamID);
                        AuthResponseDTO teamInfo = credentials.GetValue(ut.teamID);
                        await slackAPI.SendMessage(teamInfo.bot.bot_access_token, ut.userID, report.ResultMessage);
                    }
                    var nextMonth = currentDay.AddMonths(1);
                    firstOfMonth = new DateTimeOffset(Utilities.NextReportDate(nextMonth)).ToUnixTimeSeconds();
                }
            }
        }
        public async Task <ActionResult <AuthResponseDTO> > Login(AccountCredentialsDTO credentials)
        {
            var user = await userManager.FindByNameAsync(credentials.Email);

            if (user == null)
            {
                return(Unauthorized());
            }
            if (!await userManager.CheckPasswordAsync(user, credentials.Password))
            {
                return(Unauthorized());
            }

            var accessToken  = tokenGenerator.GenerateAccessToken(user);
            var refreshToken = tokenGenerator.GenerateRefreshToken();

            context.RefreshTokens.Add(new RefreshToken
            {
                Token      = refreshToken,
                Expiration = DateTime.Now.Add(tokenGenerator.Options.RefreshExpiration),
                UserId     = user.Id
            });
            context.SaveChanges();

            var response = new AuthResponseDTO
            {
                AccessToken  = accessToken,
                RefreshToken = refreshToken,
                UserId       = user.Id,
                Username     = user.UserName
            };

            return(response);
        }
Exemple #3
0
        public async Task <ActionResult <AuthResponseDTO> > Login(AccountCredentialsDTO credentials)
        {
            var user = await userManager.FindByNameAsync(credentials.Email);

            if (user == null)
            {
                return(Unauthorized());
            }

            if (!await userManager.CheckPasswordAsync(user, credentials.Password))
            {
                return(Unauthorized());
            }

            var accessToken = tokenGenerator.GenerateAccessToken(user);

            var authUser = new AuthResponseDTO
            {
                AccessToken = accessToken,
                UserId      = user.Id,
                UserName    = user.UserName
            };

            return(authUser);
        }
Exemple #4
0
        public async Task <AuthResponseDTO> RequestTokenAsync([FromBody] OsuTokenRequestDTO tokenRequestDto)
        {
            // To auth a code - https://osu.ppy.sh/oauth/authorize?client_id=4309&redirect_uri=http://localhost:61899/osu/callback&response_type=code&scope=identify public&state=chicken

            string clientSecret = Environment.GetEnvironmentVariable("OsuRequest_Osu_ClientSecret");

            if (clientSecret == null)
            {
                throw new HttpResponseException();
            }

            AuthRequestDTO authRequestDto = new AuthRequestDTO()
            {
                ClientId     = 4309,
                ClientSecret = clientSecret,
                Code         = tokenRequestDto.Code,
                GrantType    = "authorization_code",
                RedirectUri  = "http://localhost:61899/osu/callback"
            };

            HttpResponseMessage response = await httpClient.PostAsync("/oauth/token", JsonContent.Create(authRequestDto, null, snakeCaseSerializerOptions));

            if (response.IsSuccessStatusCode)
            {
                AuthResponseDTO authResponse = await response.Content.ReadFromJsonAsync <AuthResponseDTO>(snakeCaseSerializerOptions);

                return(authResponse);
            }

            throw new HttpResponseException()
                  {
                      Status = (int)response.StatusCode,
                      Value  = await response.Content.ReadAsStringAsync()
                  };
        }
Exemple #5
0
 public void SetValue(string teamID, AuthResponseDTO response)
 {
     using (var connection = new SqliteConnection(connectionString))
     {
         connection.Execute(@"insert or replace into TeamCredentials (TeamID, Credentials) values (@TeamID, @Credentials)", new { TeamID = teamID, Credentials = JsonConvert.SerializeObject(response) });
     }
 }
        private async Task SendAlerts()
        {
            var nextAlarm = Utilities.CalculateSeconds(DateTime.Now);
            var users     = userPreferences.GetUsers(currentTime, nextAlarm);

            foreach (UserTeam ut in users)
            {
                AuthResponseDTO teamInfo = credentials.GetValue(ut.teamID);
                await slackAPI.SendMessage(teamInfo.bot.bot_access_token, ut.userID, $"Your alert!");
            }
            currentTime = nextAlarm;
        }
Exemple #7
0
        public async Task RequestTokenAsync(string code)
        {
            OsuTokenRequestDTO osuTokenRequestDto = new OsuTokenRequestDTO()
            {
                Code = code
            };

            HttpResponseMessage response = await authHttpClient.PostAsync("/auth/osu/token", JsonContent.Create(osuTokenRequestDto));

            if (response.IsSuccessStatusCode)
            {
                AuthResponseDTO authResponse = await response.Content.ReadFromJsonAsync <AuthResponseDTO>();

                accessToken = authResponse.AccessToken;

                osuHttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            }
        }
Exemple #8
0
        private async Task Load()
        {
            try
            {
                if (EmplID.Text != null && UserPass.Text != null)
                {
                    AuthResponseDTO response = await AuthenticateLogin(EmplID.Text, UserPass.Text);

                    if (response.LoginSuccessful)
                    {
                        FormsAuthentication.SetAuthCookie(EmplID.Text, true);

                        FormsAuthenticationTicket ticket1 =
                            new FormsAuthenticationTicket(
                                1,                                                                 // version
                                EmplID.Text,                                                       // get username  from the form
                                DateTime.Now,                                                      // issue time is now
                                DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes), // expires in 20 minutes
                                true,                                                              // cookie is not persistent
                                "User"                                                             // role assignment is stored
                                                                                                   // in userData
                                );
                        HttpCookie cookie1 = new HttpCookie(
                            FormsAuthentication.FormsCookieName,
                            FormsAuthentication.Encrypt(ticket1));
                        Response.Cookies.Add(cookie1);

                        Response.Redirect("~/statusupdate.aspx");
                    }
                    else
                    {
                        //ModelState.AddModelError("", response.ErrorMessage);
                        InvalidCredentialsMessage.Text    = response.ErrorMessage;
                        InvalidCredentialsMessage.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                InvalidCredentialsMessage.Text    = ex.Message;
                InvalidCredentialsMessage.Visible = true;
            }
        }
Exemple #9
0
        private async Task <AuthResponseDTO> AuthenticateLogin(string serialNumber, string password)
        {
            try
            {
                AuthResponseDTO result = new AuthResponseDTO();

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(LdapAuthenticationServiceUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //Specify what LDAP attributes need to be returned when a user's authentication is passed
                    AuthRequestDTO authRequest = new AuthRequestDTO {
                        UserId = serialNumber, Password = password, LoginRequested = true, AuthenticatedMode = AuthenticatedModes.CityOfLA
                    };
                    authRequest.LdapAttributes = new Dictionary <string, string>();
                    authRequest.LdapAttributes.Add(LdapAttributeName.FULLNAME, "");
                    authRequest.LdapAttributes.Add(LdapAttributeName.SURNAME, "");

                    var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(authRequest);

                    HttpResponseMessage response = await client.PostAsJsonAsync("api/auth", authRequest);

                    if (response.IsSuccessStatusCode)
                    {
                        AuthResponseDTO authResponse = await response.Content.ReadAsAsync <AuthResponseDTO>();

                        result = authResponse;
                    }
                    else
                    {
                        throw new Exception("Authentication: " + response.StatusCode + " " + response.ReasonPhrase);
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <ActionResult <AuthResponseDTO> > Refresh(string oldRefreshToken)
        {
            var token = await context.RefreshTokens.FindAsync(oldRefreshToken);

            if (token == null)
            {
                return(BadRequest());
            }

            context.RefreshTokens.Remove(token);

            if (token.Expiration < DateTime.Now)
            {
                return(BadRequest());
            }

            var user = await userManager.FindByIdAsync(token.UserId);

            var accessToken  = tokenGenerator.GenerateAccessToken(user);
            var refreshToken = tokenGenerator.GenerateRefreshToken();

            context.RefreshTokens.Add(new RefreshToken
            {
                Token      = refreshToken,
                Expiration = DateTime.Now.Add(tokenGenerator.Options.RefreshExpiration),
                UserId     = user.Id
            });
            context.SaveChanges();

            var response = new AuthResponseDTO
            {
                AccessToken  = accessToken,
                RefreshToken = refreshToken,
                UserId       = user.Id,
                Username     = user.UserName
            };

            return(response);
        }
 public IActionResult GetAuthTokens(AuthResponseDTO response)
 {
     repository.SetValue(response.team_id, response);
     return(Ok());
 }