Example #1
0
        public HttpResponseMessage Login([FromBody] LoginApiModel apiModel)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            ResponseFormat responseData;

            if (apiModel == null)
            {
                response.StatusCode  = HttpStatusCode.BadRequest;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.INVALID_BODY;
            }
            else
            {
                var validate = _userService.ValidatePassword(apiModel.email, apiModel.password);
                if (validate.Item1 == true)
                {
                    var dbUser = _userRepository.GetByEmail(validate.Item3.Email);
                    //generate jwt token
                    var JwtToken = JwtTokenManager.GenerateJwtToken(validate.Item3);
                    //generate refresh token
                    var           RefreshToken    = JwtTokenManager.GenerateRefreshToken();
                    REFRESH_TOKEN newRefreshToken = new REFRESH_TOKEN();
                    newRefreshToken.USER_ID = dbUser.ID;
                    newRefreshToken.Token   = RefreshToken;
                    db.REFRESH_TOKEN.Add(newRefreshToken);
                    db.SaveChanges();

                    //set refresh token to httponly and add it to cookies
                    //var nv = new NameValueCollection();
                    //nv["refreshToken"] = RefreshToken;
                    //nv["seriesIdentifier"] = dbUser.ID.ToString();
                    //nv["tokenIdentifier"] = newRefreshToken.ID.ToString();
                    response.Headers.Add("set-cookie", $"refreshTokenData=refreshToken={RefreshToken}&seriesIdentifier={dbUser.ID}&tokenIdentifier={newRefreshToken.ID}; path=/; SameSite=None; Secure; max-age=2592000");

                    //create response data
                    responseData = ResponseFormat.Success;
                    if (dbUser.Avatar != null)
                    {
                        responseData.data = new
                        {
                            user = new
                            {
                                id        = validate.Item3.ID,
                                username  = validate.Item3.Username,
                                firstName = validate.Item3.FirstName,
                                lastName  = validate.Item3.LastName,
                                jwt       = JwtToken,
                                group     = dbUser.GROUP.ID,
                                avatar    = $"{StaticStrings.ServerHost}avatar?fileName={dbUser.Avatar}"
                            }
                        };
                    }
                    else
                    {
                        responseData.data = new
                        {
                            user = new
                            {
                                id        = validate.Item3.ID,
                                username  = validate.Item3.Username,
                                firstName = validate.Item3.FirstName,
                                lastName  = validate.Item3.LastName,
                                jwt       = JwtToken,
                                group     = dbUser.GROUP.ID,
                                avatar    = ""
                            }
                        };
                    }

                    if (string.IsNullOrEmpty(dbUser.CalendarId))
                    {
                        try
                        {
                            var calId = googleCalendar.AddCalendar(dbUser.Email);
                            googleCalendar.AddPeopleToAcl(dbUser.Email, calId, true);
                            _userService.UpdateCalendarId(dbUser.Email, calId);
                        }
                        catch
                        {
                        }
                    }
                    response.StatusCode = HttpStatusCode.OK;
                }
                else
                {
                    response.StatusCode  = HttpStatusCode.Unauthorized;
                    responseData         = ResponseFormat.Fail;
                    responseData.message = validate.Item2;
                }
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
Example #2
0
        public HttpResponseMessage Refresh()
        {
            string c_refreshToken        = "";
            string c_series              = "";
            string t_series              = "";
            HttpResponseMessage response = new HttpResponseMessage();
            ResponseFormat      responseData;

            CookieHeaderValue cookie = Request.Headers.GetCookies("refreshTokenData").FirstOrDefault();

            if (cookie != null)
            {
                CookieState cookieState = cookie["refreshTokenData"];
                c_refreshToken = cookieState["refreshToken"];
                c_series       = cookieState["seriesIdentifier"];
                t_series       = cookieState["tokenIdentifier"];
                var dbUser = db.USERs.Find(int.Parse(c_series));

                if (dbUser != null)
                {
                    //look for token
                    var temp = int.Parse(t_series);
                    //var a = WebUtility.UrlDecode(c_refreshToken);
                    var a       = Base64UrlEncoder.Decode(c_refreshToken);
                    var dbToken = dbUser.REFRESH_TOKEN.Where(c => c.ID == temp).FirstOrDefault();
                    if (dbToken != null)
                    {
                        if (c_refreshToken == dbToken.Token)
                        {
                            var user = AutoMapper.Mapper.Map <User>(dbUser);
                            //grab a new jwt token
                            var JwtToken = JwtTokenManager.GenerateJwtToken(user);
                            //grab a new refresh token
                            var RefreshToken = JwtTokenManager.GenerateRefreshToken();
                            //store new value for token
                            dbToken.Token = RefreshToken;
                            db.SaveChanges();
                            //response.Headers.Add("set-cookie", $"refreshTokenData=refreshToken={RefreshToken}&seriesIdentifier={dbUser.ID}&tokenIdentifier={dbToken.ID}; path=/; SameSite=None; Secure; max-age=2592000");
                            response.Headers.Add("set-cookie", $"refreshTokenData=refreshToken={RefreshToken}&seriesIdentifier={dbUser.ID}&tokenIdentifier={dbToken.ID}; path=/; SameSite=None; Secure; max-age=2592000");
                            //build response data
                            responseData = ResponseFormat.Success;

                            if (dbUser.Avatar != null)
                            {
                                responseData.data = new
                                {
                                    user = new
                                    {
                                        id        = user.ID,
                                        username  = user.Username,
                                        firstName = user.FirstName,
                                        lastName  = user.LastName,
                                        jwt       = JwtToken,
                                        group     = dbUser.GROUP.ID,
                                        avatar    = $"{StaticStrings.ServerHost}avatar?fileName={dbUser.Avatar}"
                                    }
                                };
                            }
                            else
                            {
                                responseData.data = new
                                {
                                    user = new
                                    {
                                        id        = user.ID,
                                        username  = user.Username,
                                        firstName = user.FirstName,
                                        lastName  = user.LastName,
                                        jwt       = JwtToken,
                                        group     = dbUser.GROUP.ID,
                                        avatar    = ""
                                    }
                                };
                            }

                            response.StatusCode = HttpStatusCode.OK;
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.Unauthorized;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = "Cookie Invalid";
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = "Cookie Invalid";
                    }
                }
                else
                {
                    response.StatusCode  = HttpStatusCode.NotFound;
                    responseData         = ResponseFormat.Fail;
                    responseData.message = "Not a valid user";
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = "No cookie found";
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }