Exemplo n.º 1
0
        public HttpResponseMessage OAuth(ServiceModel.OAuthSignInModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.ToJson()));
            }

            //validate user
            var    provider = AuthFactory.GetProvider(model.Provider, model.AuthToken);
            var    userInfo = provider.GetUser();
            string userId   = userInfo.UserId;

            if (string.IsNullOrWhiteSpace(userId))
            {
                ModelState.AddModelError("", string.Format("{0} could not locate a user using the provided auth token."));
                return(Request.CreateResponse(HttpStatusCode.Unauthorized, ModelState.ToJson()));
            }

            //get actual user
            var user = context.GetAll <DomainModel.User>()
                       .FirstOrDefault(u => u.OAuthProvider.Equals(model.Provider, StringComparison.OrdinalIgnoreCase) && u.OAuthUserId.Equals(userId, StringComparison.OrdinalIgnoreCase));

            if (user == null)
            {
                //try to find users by existing email address (mostly to clean up v1)
                if (!string.IsNullOrWhiteSpace(userInfo.Email))
                {
                    user = context.GetAll <DomainModel.User>()
                           .FirstOrDefault(u => u.EmailAddress.Equals(userInfo.Email, StringComparison.OrdinalIgnoreCase));
                }

                //user really is new, lets create them
                if (user == null)
                {
                    user = new DomainModel.User(model.Provider, userId);
                    context.Add(user);
                }

                user.EmailAddress = userInfo.Email;
                user.ImagePath    = userInfo.PictureUrl;
                user.FirstName    = userInfo.FirstName;
                user.LastName     = userInfo.LastName;

                if (string.IsNullOrWhiteSpace(user.ImagePath))
                {
                    var defaultImage = new Uri(Request.RequestUri, "/images/GenericUserImage.gif");
                    user.ImagePath = defaultImage.ToString();
                }

                context.SaveChanges();
            }

            //FormsAuthentication.SetAuthCookie(user.EmailAddress, true);
            return(Request.CreateResponse(HttpStatusCode.OK, user.MapToServiceModel()));
        }