Ejemplo n.º 1
0
        public async Task <IActionResult> LoginAsync([FromBody] loginRequest request)
        {
            IActionResult response      = Unauthorized();
            string        tokenFireBase = null;
            string        tokenFcm      = null;

            try
            {
                tokenFireBase = request.firebaseToken;
                tokenFcm      = request.tokenFcm;
                FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance
                                             .VerifyIdTokenAsync(tokenFireBase);

                LoginService service = new LoginService(_unitOfWork, _config);
                string       json    = service.loginFireBase(decodedToken, tokenFcm);
                if (json != null)
                {
                    response = Ok(json);
                }
                else
                {
                    response = NotFound();
                }
            }
            catch (Exception e)
            {
                response = Unauthorized(e.Message);
            }
            return(response);
        }
Ejemplo n.º 2
0
        public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            var userPrincipal = context.Principal;

            var token = userPrincipal.Claims.FirstOrDefault(c => c.Type == "Firebase-Token")?.Value;

            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(token);

                    if (new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc).AddSeconds(decodedToken.ExpirationTimeSeconds) > DateTime.UtcNow)
                    {
                        return;
                    }
                }
                catch
                {
                    context.RejectPrincipal();
                    await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                }
            }
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
Ejemplo n.º 3
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(((FirebaseToken != null ? FirebaseToken.GetHashCode() : 0) * 397) ^ (NotificationTypeId != null ? NotificationTypeId.GetHashCode() : 0));
     }
 }
Ejemplo n.º 4
0
        public IActionResult MarkEmailAsReadUnread(string authSessionCookie, int emailId, string readOrUnread)
        {
            FirebaseToken firebaseToken = FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(authSessionCookie).Result;
            string        firebaseUid   = firebaseToken.Uid;

            using (DatabaseContext database = new DatabaseContext())
            {
                User user = database.Users.Single(u => u.FirebaseUid == firebaseUid);

                UserEmail userEmailToMark = database.UserEmails.Single(ue => ue.EmailId == emailId && ue.ReceivingUsername == user.Username);

                switch (readOrUnread)
                {
                case "read":
                    userEmailToMark.MarkedAsRead = true;
                    break;

                case "unread":
                    userEmailToMark.MarkedAsRead = false;
                    break;

                default:
                    return(Content("invalid or missing parameter: readOrUnread"));
                }

                return(Content("success"));
            }
        }
Ejemplo n.º 5
0
        public async Task <EmployeeDto> Login(FirebaseToken userToken)
        {
            string email = userToken.Claims["email"].ToString();

            if (!AppUtils.CheckValidationEmail(email))
            {
                throw new ArgumentException("Wrong format input email");
            }

            Employee emp = await _uow.EmployeeRepository.GetFirst(filter : el => el.Email == email, includeProperties : "Role");

            // check if this email belongs to fpt.edu.vn

            if (emp == null)
            {
                _uow.EmployeeRepository.Add(new Employee()
                {
                    Email      = email,
                    Fullname   = userToken.Claims["name"].ToString(),
                    CreateTime = DateTime.Now,
                    RoleId     = AppConstants.Roles.Employee.ID,
                });

                if (await _uow.SaveAsync() > 0)
                {
                    emp = await _uow.EmployeeRepository.GetFirst(filter : el => el.Email == email, includeProperties : "Role");
                }
                else
                {
                    throw new Exception("Create new account failed");
                }
            }
            return(_mapper.Map <EmployeeDto>(emp));
        }
Ejemplo n.º 6
0
        public IActionResult DeclineMinistryInvite(string authSessionCookie, string ministry, string newCountryName)
        {
            FirebaseToken firebaseToken = FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(authSessionCookie).Result;
            string        firebaseUid   = firebaseToken.Uid;

            using (DatabaseContext database = new DatabaseContext())
            {
                User user = database.Users.Single(u => u.FirebaseUid == firebaseUid);

                Country newCountry = database.Countries.Single(c => c.CountryName == newCountryName);

                MinistryHelper.MinistryCode ministryCode = (MinistryHelper.MinistryCode)Enum.Parse(typeof(MinistryHelper.MinistryCode), ministry);

                if (database.InvitedMinisters.Any(im => im.Username == user.Username && im.CountryName == newCountry.CountryName && im.Ministry == ministryCode))
                {
                    InvitedMinister invitedMinister = database.InvitedMinisters.Single(im => im.Username == user.Username && im.CountryName == newCountry.CountryName && im.Ministry == ministryCode);
                    database.InvitedMinisters.Remove(invitedMinister);

                    Notification notification = NotificationHelper.GenerateMinisterialInvitationDeclinedNotification(database.Users.Single(u => u.CountryName == newCountry.CountryName && u.Ministry == MinistryHelper.MinistryCode.PrimeMinister).Username, user.Username, ministryCode);
                    database.Notifications.Add(notification);

                    database.SaveChanges();

                    return(Content("success"));
                }
                else
                {
                    return(StatusCode(403));
                }
            }
        }
Ejemplo n.º 7
0
        public IActionResult CancelMinistryInvite(string authSessionCookie, string ministry)
        {
            FirebaseToken firebaseToken = FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(authSessionCookie).Result;
            string        firebaseUid   = firebaseToken.Uid;

            using (DatabaseContext database = new DatabaseContext())
            {
                User user = database.Users.Single(u => u.FirebaseUid == firebaseUid);

                Country country = database.Countries.Single(c => c.CountryName == user.CountryName);

                MinistryHelper.MinistryCode ministryCode = (MinistryHelper.MinistryCode)Enum.Parse(typeof(MinistryHelper.MinistryCode), ministry);

                if (user.Ministry == MinistryHelper.MinistryCode.PrimeMinister)
                {
                    InvitedMinister invitedMinister = database.InvitedMinisters.Single(im => im.CountryName == country.CountryName && im.Ministry == ministryCode);
                    database.InvitedMinisters.Remove(invitedMinister);

                    return(Content("success"));
                }
                else
                {
                    return(StatusCode(403));
                }
            }
        }
Ejemplo n.º 8
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
                if (token != null)
                {
                    FirebaseToken decodedJwtToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(token);

                    object isAdmin;
                    if (decodedJwtToken.Claims.TryGetValue("student", out isAdmin))
                    {
                        if ((bool)isAdmin)
                        {
                            context.Items["roles"]  = new string[] { "student" };
                            context.Items["userId"] = decodedJwtToken.Uid;
                        }
                    }
                }
            }
            finally
            {
                await _next(context);
            }
        }
        public async Task <UsuarioFirebase> obtener_usuario(string idToken)
        {
            UsuarioFirebase usuario      = new UsuarioFirebase();
            FirebaseToken   decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);

            //Sirve para poner claims a un token
            //var prueba = new Dictionary<string, object>()
            //{
            //{ "admin", true },
            //};
            //await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(decodedToken.Uid, prueba);
            usuario.Uid = decodedToken.Uid;
            var    claims = decodedToken.Claims;
            object isAdmin, isSeller;

            if (claims.TryGetValue("admin", out isAdmin))
            {
                if ((bool)isAdmin)
                {
                    usuario.admin = true;
                }
            }
            if (claims.TryGetValue("seller", out isSeller))
            {
                if ((bool)isSeller)
                {
                    usuario.seller = true;
                }
            }
            return(usuario);
        }
Ejemplo n.º 10
0
        public async Task <Account> RegisterViaToken(string firebaseToken)
        {
            FirebaseToken token = await DecodeToken(firebaseToken);

            string providerId = token.Uid;

            Login existingLogin = await FindLogin(Providers.Google, providerId);

            if (existingLogin != null)
            {
                return(null);
            }
            string name    = token.Claims.FirstOrDefault(claim => claim.Key == "name").Value.ToString();
            string picture = token.Claims.FirstOrDefault(claim => claim.Key == "picture").Value.ToString();

            Account account = new Account(name);

            account.UpdatePicture(picture);
            await _accountRepo.Add(account);

            Login login = new Login(account, Providers.Google, providerId, string.Empty);
            await _loginRepo.Add(login);

            return(account);
        }
Ejemplo n.º 11
0
        public async Task <ActionResult> Post([FromBody] JsonElement json)
        {
            string authHeader    = this.HttpContext.Request.Headers["Authorization"];
            string route         = this.HttpContext.Request.Headers["Route"];
            string collectionsId = "";

            if (this.HttpContext.Request.Headers["collectionsId"] != "")
            {
                collectionsId = this.HttpContext.Request.Headers["collectionsId"];
            }
            FirebaseToken auth = await validate(authHeader);

            if (auth.ExpirationTimeSeconds > DateTimeOffset.Now.ToUnixTimeSeconds())
            {
                switch (route)
                {
                case "NewUser":
                    new FirebaseUser(auth.Claims["email"].ToString(), auth.Uid);
                    return(Ok());

                case "BuildSimulation":
                    return(BuildSimulation(json.GetRawText(), collectionsId));
                }
            }
            return(Ok());
        }
Ejemplo n.º 12
0
        public async Task <AccessTokenResponse> RegisterExternalUsingFirebaseAsync(FirebaseRegisterExternal external)
        {
            FirebaseRegisterExternalValidation validation = new FirebaseRegisterExternalValidation();

            validation.ValidateAndThrow(external);

            FirebaseToken decodedToken = validation.ParsedToken;

            var    claims = decodedToken.Claims;
            string email  = claims["email"] + "";
            string name   = claims["name"] + "";
            string avatar = claims["picture"] + "";

            var user = repository.GetUserByUsername(email);

            if (user == null)
            {
                user = new User()
                {
                    Email    = email,
                    Username = email,
                    Fullname = name
                };
                user.UserRole.Add(new UserRole()
                {
                    RoleId = (int)RolesEnum.MEMBER
                });
                await this.repository.AddAsync(user);
            }

            return(CreateToken(user));
        }
Ejemplo n.º 13
0
        private AuthenticationTicket BuildTicket(FirebaseToken token)
        {
            var claims    = BuildClaims(token);
            var identity  = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);

            return(new AuthenticationTicket(principal, Scheme.Name));
        }
Ejemplo n.º 14
0
 private static Claim[] BuildClaims(FirebaseToken token)
 {
     return(new[]
     {
         new Claim(ClaimTypes.Name, token.Claims["name"].ToString()),
         new Claim(ClaimTypes.Email, token.Claims["email"].ToString()),
         new Claim(ClaimTypes.NameIdentifier, token.Claims["user_id"].ToString())
     });
 }
Ejemplo n.º 15
0
        public async Task <AccountDataset> Login(FirebaseToken userToken, string flg)
        {
            Models.Account account = await _uow.AccountRepository.GetAccountByEmail(userToken.Claims["email"].ToString());

            if (account == null)
            {
                Models.Account newAccount = new Models.Account()
                {
                    Email = userToken.Claims["email"].ToString()
                };
                _uow.AccountRepository.Insert(newAccount);
                if (flg == CVideoConstant.Client.Employee)
                {
                    newAccount.RoleId = CVideoConstant.Roles.Employee.Id;
                    _uow.EmployeeRepository.Insert(new Models.Employee()
                    {
                        Account     = newAccount,
                        FullName    = userToken.Claims["name"].ToString(),
                        Avatar      = userToken.Claims["picture"].ToString(),
                        DateOfBirth = DateTime.UtcNow
                    });
                }
                else if (flg == CVideoConstant.Client.Employer)
                {
                    newAccount.RoleId = CVideoConstant.Roles.Employer.Id;
                    _uow.CompanyRepository.Insert(new Models.Company()
                    {
                        Account     = newAccount,
                        CompanyName = userToken.Claims["name"].ToString(),
                        Avatar      = userToken.Claims["picture"].ToString()
                    });
                }
                else
                {
                    throw new ArgumentException("Flag is invalid");
                }
                if (await _uow.CommitAsync() > 0)
                {
                    account = await _uow.AccountRepository.GetFirst(filter : acc => acc.AccountId == newAccount.AccountId, includeProperties : "Role");
                }
                else
                {
                    throw new Exception("Create new account failed");
                }
            }
            else
            {
                if ((flg == CVideoConstant.Client.Employee && account.Role.RoleName != CVideoConstant.Roles.Employee.Name) ||
                    (flg == CVideoConstant.Client.Employer && account.Role.RoleName != CVideoConstant.Roles.Employer.Name) ||
                    (flg == CVideoConstant.Client.Admin && account.Role.RoleName != CVideoConstant.Roles.Admin.Name))
                {
                    return(null);
                }
            }
            return(_mapper.Map <AccountDataset>(account));
        }
Ejemplo n.º 16
0

        
Ejemplo n.º 17
0
        public async Task <IActionResult> GetAuthParamsAsync()
        {
            string idToken = Request.Headers.FirstOrDefault(x => x.Key == "Authorization").Value;

            idToken = idToken.Replace("Bearer ", "");

            FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);

            return(Ok(decodedToken.Uid));
        }
Ejemplo n.º 18
0
        public async Task <ActionResult> GetLogin(string email = "*****@*****.**", string password = "******")
        {
            if (email == "" || password == "")
            {
                return(BadRequest("InCorrect Login Input"));
                // return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }



            //Student student = db.GetAll<Student>().FirstOrDefault(s => s.Id == studentId);

            //Student student = db.GetAll<Student>().FirstOrDefault(s => s.User.Email ==email && password==password);

            InMemoryRepository repository = new InMemoryRepository();

            //var permissionProvider = MyPermissionsProvider.GetPermissionsByEmail(email);

            //if(HTTPContext.Permissions.Contains(AppPermissions.Read_secure) student.secureInfo = await _repo.getStudentSecure(student.id);
            //if(HTTPContext.Permissions.Contains(AppPermissions.Student.Delete) request.actions.Add(delete); request._links.add(new link(/students/idadsf, method: DELETE);

            //string hostname = "localhost:54011";
            var institution = await _institutionService.GetInstitutionByHost(HttpContext.Request.Host.ToString());

            FirebaseToken decodedToken = null;
            UserClaims    userClaims;

            try
            {
                decodedToken =
                    await _firebaseUtils.ValidateCredentials(email.Trim().ToLower(), password);
            }
            catch (Exception ex)
            {
                if (ex is BadUserOrPasswordException)
                {
                    return(StatusCode(418));
                }
                throw;
            }

            try
            {
                userClaims =
                    await _claimsUtils.GetClaimsPrincipal(decodedToken, UserAuthType.Admin, institution.GUID);

                // Here to get access and permission
            }
            catch (Exception ex)
            {
                return(StatusCode(418));
            }

            return(Ok());
        }
Ejemplo n.º 19
0
        internal static async Task VeridyIdTokenAsync(string idToken)
        {
            // [START verify_id_token]
            FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance
                                         .VerifyIdTokenAsync(idToken);

            string uid = decodedToken.Uid;

            // [END verify_id_token]
            Console.WriteLine("Decoded ID token from user: {0}", uid);
        }
Ejemplo n.º 20
0
        private async Task <bool> ParseToken(string fToken, CancellationToken cancellation)
        {
            try
            {
                this.ParsedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(fToken);

                return(true);
            }catch (Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 21
0
        public async Task <string> Get()
        {
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(@"D:\Datos Matias\firebase\Private Key\usuario-5093e-firebase-adminsdk-43fcf-1bf89503c6.json"),
            });
            FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(cadena);

            string uid = decodedToken.Uid;

            return(uid);
        }
Ejemplo n.º 22
0
        public async Task <ActionResult> GetCurrent()
        {
            string accessToken = Request.Headers[HeaderNames.Authorization];

            var jwtToken = accessToken.Replace("Bearer ", string.Empty);

            FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(jwtToken);

            var user = await FirebaseAuth.DefaultInstance.GetUserAsync(decodedToken.Uid);

            return(Ok(user));
        }
Ejemplo n.º 23
0
        public async Task <FirebaseToken> ValidateFirebaseToken(string tokenStr)
        {
            FirebaseToken decodedToken = null;

            try
            {
                decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(tokenStr);
            }
            catch (FirebaseAuthException)
            {
            }
            return(decodedToken);
        }
Ejemplo n.º 24
0
        public Model.DTO.UserFirebase GetData(string tokenId)
        {
            FirebaseToken decodedToken = FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(tokenId).Result;
            UserRecord    userInfo     = FirebaseAuth.DefaultInstance.GetUserAsync(decodedToken.Uid).Result;

            return(new Model.DTO.UserFirebase
            {
                UID = decodedToken.Uid,
                Name = GetNombre(decodedToken, userInfo),
                Email = GetEmail(decodedToken, userInfo),
                Picture = GetPicture(decodedToken, userInfo)
            });
        }
Ejemplo n.º 25
0

        
Ejemplo n.º 26
0
        public IActionResult CreateACountryPOST()
        {
            string authSessionCookie = Request.Cookies["authSession"];

            bool userLoggedIn = FirebaseAuthHelper.IsUserLoggedIn(authSessionCookie);

            if (userLoggedIn)
            {
                FirebaseToken firebaseToken = FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(authSessionCookie).Result;
                string        firebaseUid   = firebaseToken.Uid;

                using (DatabaseContext database = new DatabaseContext())
                {
                    User user = database.Users.Single(u => u.FirebaseUid == firebaseUid);

                    if (user.CountryName == null)
                    {
                        Country country = new Country
                        {
                            CountryName = Request.Form["country-name"],
                            CapitalName = Request.Form["capital-name"],
                            FlagId      = CountryGenerationHelper.FlagNameToId(Request.Form["flag-name"])
                        };

                        if (database.Countries.Any(c => c.CountryName == country.CountryName))
                        {
                            ViewData["errorMessage"] = "There is another country with that name, and we don't allow duplicate country names. Sorry!";
                            return(View("../Error/TextError"));
                        }

                        database.Countries.Add(country);
                        user.CountryName = country.CountryName;
                        user.Ministry    = MinistryHelper.MinistryCode.PrimeMinister;
                        database.SaveChanges();

                        return(Redirect("/"));
                    }
                    else
                    {
                        ViewData["errorMessage"] = "You are already a minister in another country.";
                        return(View("../Error/TextError"));
                    }
                }
            }
            else
            {
                ViewData["errorMessage"] = "You are not logged in.";
                return(View("../Error/TextError"));
            }
        }
Ejemplo n.º 27
0
        public async Task <ActionResult> Get()
        {
            string        authHeader = this.HttpContext.Request.Headers["Authorization"];
            FirebaseToken auth       = await validate(authHeader);

            string route         = this.HttpContext.Request.Headers["Route"];
            string collectionsId = "";

            if (this.HttpContext.Request.Headers["collectionsId"] != "")
            {
                collectionsId = this.HttpContext.Request.Headers["collectionsId"];
            }
            string accountId = "";

            if (this.HttpContext.Request.Headers["accountId"] != "")
            {
                accountId = this.HttpContext.Request.Headers["accountId"];
            }
            DateTime startDate = DateTime.Now;

            if (this.HttpContext.Request.Headers["startDate"].Count() != 0)
            {
                startDate = DateConvert(this.HttpContext.Request.Headers["startDate"]);
            }
            DateTime endDate = DateTime.Now;

            if (this.HttpContext.Request.Headers["endDate"].Count() != 0)
            {
                endDate = DateConvert(this.HttpContext.Request.Headers["endDate"]);
            }
            if (auth.ExpirationTimeSeconds > DateTimeOffset.Now.ToUnixTimeSeconds())
            {
                switch (route)
                {
                case "UnseenCount":
                    return(UnseenCount(auth.Claims["email"].ToString()));

                case "Index":
                    return(Index(auth.Claims["email"].ToString()));

                case "GetAccounts":
                    return(GetAccounts(collectionsId));

                case "GetReportedTransaction":
                    return(GetReportedTransactions(accountId, startDate, endDate));
                }
            }
            return(Ok());
        }
Ejemplo n.º 29
0
        public async Task <(User user, string accessToken, string refreshToken)> LoginSocialAsync(LoginSocialRequest loginSocialRequest)
        {
            FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(loginSocialRequest.Token);

            string     uid        = decodedToken.Uid;
            UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserAsync(uid);

            var    pwd      = new Password();
            string password = pwd.Next();
            User   user     = await SignUpAsync(new SignUpRequest { FullName = userRecord.DisplayName, Email = userRecord.Email, Password = password, Social = true });

            Tokens tokens = await SetTokenAsync(user);

            return(user, tokens.Token, tokens.RefreshToken);
        }
Ejemplo n.º 30
0
        public static async Task <string> Verify(this AuthedRequest token)
        {
            try
            {
                FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance
                                             .VerifyIdTokenAsync(token.JwtToken);

                return(decodedToken.Uid);
            }
            catch (Exception e)
            {
                Log.Information(e, $"Unauthorised user request token: {token.JwtToken}");
                return(null);
            }
        }