Example #1
0
        public async Task <IHttpActionResult> Suggestion([FromBody] AuthorizedUser authorizedUser)
        {
            this.authenticateUser(authorizedUser);
            UserAccount retrievedUser = await authorizedUser.getUserAccount(db).ConfigureAwait(false);

            await retrievedUser.Login().ConfigureAwait(false);

            TilerUser tilerUser = retrievedUser.getTilerUser();

            tilerUser.updateTimeZoneTimeSpan(authorizedUser.getTimeSpan);
            if (retrievedUser.Status)
            {
                DateTimeOffset nowTime = authorizedUser.getRefNow();
                if (retrievedUser.ScheduleLogControl.Now == null)
                {
                    var         retrievalOption = DataRetrievalSet.analysisManipulation;
                    DB_Schedule schedule        = new DB_Schedule(retrievedUser, nowTime, authorizedUser.getCurrentLocation(), retrievalOptions: retrievalOption);
                    retrievedUser.ScheduleLogControl.Now = schedule.Now;
                }

                await SuggestionAnalysis(retrievedUser.ScheduleLogControl, authorizedUser.getCurrentLocation()).ConfigureAwait(false);
            }

            var retValue = new PostBackData("", 0);

            return(Ok(retValue.getPostBack));
        }
Example #2
0
        async public Task <UserAccountDirect> LoginStatic(LoginViewModel model)
        {
            UserAccountDirect RetValue    = null;
            string            LoopBackUrl = "";

            if (!ModelState.IsValid)
            {
                string AllErrors = string.Join("\n", ModelState.Values.SelectMany(obj => obj.Errors.Select(obj1 => obj1.ErrorMessage)));
                return(RetValue);
            }



            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
            {
                UserController myUserCtrl  = new UserController();
                TilerUser      SessionUser = await myUserCtrl.GetUser(User.Identity.GetUserId(), User.Identity.GetUserName());

                RetValue = new UserAccountDirect(SessionUser.Id, dbContext);
                return(RetValue);
            }

            default:
            {
                return(RetValue);
            }
            }
        }
Example #3
0
        async Task <bool> PopulateGoogleAuthentication(string TilerUserID, string AccessToken, string RefreshToken, string GoogleEmail, DateTimeOffset ExpirationDate)
        {
            //ApplicationDbContext db = new ApplicationDbContext();
            TilerUser AppUser  = UserManager.FindById(TilerUserID);
            bool      RetValue = false;

            try
            {
                ThirdPartyCalendarAuthenticationModel NewAccountCalendarImportation = new ThirdPartyCalendarAuthenticationModel();
                string AuthenticationID = Guid.NewGuid().ToString();
                NewAccountCalendarImportation.TilerID      = TilerUserID;
                NewAccountCalendarImportation.ID           = AuthenticationID;
                NewAccountCalendarImportation.Token        = AccessToken;
                NewAccountCalendarImportation.RefreshToken = RefreshToken;
                NewAccountCalendarImportation.isLongLived  = false;
                NewAccountCalendarImportation.Email        = GoogleEmail;
                NewAccountCalendarImportation.Deadline     = ExpirationDate;
                NewAccountCalendarImportation.ProviderID   = ThirdPartyControl.CalendarTool.google.ToString();


                //await NewAccountCalendarImportation.refreshAuthenticationToken().ConfigureAwait(false);

                HttpContext myContext = System.Web.HttpContext.Current;
                ThirdPartyCalendarAuthenticationModelsController thirdPartyController = new ThirdPartyCalendarAuthenticationModelsController();
                await thirdPartyController.CreateGoogle(NewAccountCalendarImportation);

                RetValue = true;
            }
            catch
            {
                RetValue = false;
            }

            return(RetValue);
        }
Example #4
0
        public DB_SubCalendarEvent(CalendarEvent calendarEvent, TilerUser Creator, TilerUserGroup users, string timeZone, string MySubEventID, EventName name, BusyTimeLine MyBusylot, DateTimeOffset EventStart, DateTimeOffset EventDeadline, TimeSpan EventPrepTime, string myParentID, bool Rigid, bool Enabled, EventDisplay UiParam, MiscData Notes, bool completeFlag, TilerElements.Location EventLocation = null, TimeLine calendarEventRange = null, ConflictProfile conflicts = null)
        {
            if (EventDeadline < EventStart)
            {
                throw new Exception("SubCalendar Event cannot have an end time earlier than the start time");
            }
            _TimeZone = timeZone;
            _Name     = name;
            _Creator  = Creator;
            _Users    = users;
            if (conflicts == null)
            {
                conflicts = new ConflictProfile();
            }
            _ConflictingEvents  = conflicts;
            _CalendarEventRange = calendarEventRange;
            //string eventName, TimeSpan EventDuration, DateTimeOffset EventStart, DateTimeOffset EventDeadline, TimeSpan EventPrepTime, TimeSpan PreDeadline, bool EventRigidFlag, bool EventRepetition, int EventSplit
            updateStartTime(EventStart);
            updateEndTime(EventDeadline);
            _EventDuration     = MyBusylot.End - MyBusylot.Start;
            BusyFrame          = MyBusylot;
            _PrepTime          = EventPrepTime;
            UniqueID           = new EventID(MySubEventID);
            this._LocationInfo = EventLocation;

            _UiParams = UiParam;
            _DataBlob = Notes;
            _Complete = completeFlag;

            this._Enabled = Enabled;
            //EventSequence = new EventTimeLine(UniqueID.ToString(), StartDateTime, EndDateTime);
            _RigidSchedule = Rigid;
            _LastReasonStartTimeChanged = this.Start;
            _calendarEvent = calendarEvent;
        }
Example #5
0
        public ActionResult Mobile()
        {
            ViewBag.Message = "Welcome To Tiler";
            TilerUser myUser = UserManager.FindById(User.Identity.GetUserId());

            return(View(myUser));
        }
Example #6
0
 public DB_EventName(TilerUser tilerUser, TilerEvent tilerEvent, string name, string id)
 {
     _Name         = name;
     _Id           = id;
     this._Creator = tilerUser;
     this._Event   = tilerEvent;
 }
Example #7
0
        /// <summary>
        /// This is to be called when you need save the last change to the database
        /// </summary>
        /// <param name="db">The database context for accessing db</param>
        /// <param name="user">The referemce tiler user</param>
        /// <returns></returns>
        public static async Task saveLatestChange(TilerDbContext db, TilerUser user)
        {
            TilerUser retrievedUser = await((db.Users) as DbSet <TilerUser>).FindAsync(user.Id).ConfigureAwait(false);

            if (user.ClearAllId != retrievedUser.ClearAllId)
            {
                retrievedUser.ClearAllId = user.ClearAllId;
            }
            retrievedUser.LastScheduleModification = DateTime.UtcNow;
            Task waitForDbSave = null;

            if (!string.IsNullOrEmpty(retrievedUser.PasswordHash))
            {
                EntityState currentState = db.Entry(retrievedUser).State;
                if (currentState == EntityState.Detached)
                {
                    db.Entry(retrievedUser).State = EntityState.Added;
                }
                db.Entry(retrievedUser).State = EntityState.Modified;
                TilerController.dbSaveChanges(db as ApplicationDbContext);
            }

            if (waitForDbSave != null)
            {
                await waitForDbSave;
            }
        }
Example #8
0
        public async Task <ActionResult> ChangeStartOfDay(ChangeStartOfDayModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            //bool isDST = Convert.ToBoolean(model.Dst);
            var result = IdentityResult.Failed(new string[] { "Invalid Time Start Of Time" });

            DateTimeOffset TimeOfDay = new DateTimeOffset();

            if (DateTimeOffset.TryParse(model.TimeOfDay, out TimeOfDay))
            {
                /*
                 * if(isDST)
                 * {
                 *  TimeOfDay=TimeOfDay.AddHours(-1);
                 * }
                 */
                TilerUser myUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());

                myUser.EndfOfDay       = TimeOfDay.DateTime;
                myUser.TimeZone        = model.TimeZone;
                myUser.EndfOfDayString = model.TimeOfDay;
                myUser.updateTimeZone();
                result = await UserManager.UpdateAsync(myUser);
            }

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", new { Message = ManageMessageId.StartOfDaySuccess }));
            }
            AddErrors(result);
            return(View(model));
        }
Example #9
0
        public async Task createAnalysis(TilerUser user)
        {
            Analysis scheduleAnalysis = Analysis.generateAnalysisObject(user);

            scheduleAnalysis.setUser(user);
            dbContext.Analysis.Add(scheduleAnalysis);
            await dbContext.SaveChangesAsync().ConfigureAwait(false);
        }
Example #10
0
        public async Task createProcrastinateCalendarEvent(TilerUser user)
        {
            DateTimeOffset now = Utility.ProcrastinateStartTime;
            CalendarEvent  procrastinateCalEvent = ProcrastinateCalendarEvent.generateProcrastinateAll(now, user, TimeSpan.FromSeconds(1), null, "UTC");

            dbContext.CalEvents.Add(procrastinateCalEvent);
            await dbContext.SaveChangesAsync().ConfigureAwait(false);
        }
Example #11
0
 public LogControlDirect(TilerUser User, ApplicationDbContext dbContext)
 {
     _TilerUser     = User;
     LogStatus      = false;
     CachedLocation = new Dictionary <string, TilerElements.Location>();
     _Context       = dbContext;
     LogStatus      = true;
     ID             = _TilerUser.Id;
     UserName       = _TilerUser.UserName;
 }
Example #12
0
        public async Task SaveUser(TilerUser user)
        {
            var store = new UserStore <TilerUser>(db);

            var manager = new ApplicationUserManager(store);
            await manager.UpdateAsync(user);

            var ctx = store.Context;
            await ctx.SaveChangesAsync();
        }
Example #13
0
        public void triggerRefreshData(TilerUser tilerUser ) {

            string who = tilerUser.Id;
            
            var context = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<TilerFront.SocketHubs.ScheduleChange>();
            dynamic triggerRefreshRequest = new JObject();
            triggerRefreshRequest.refreshData = new JObject();
            triggerRefreshRequest.refreshData.trigger = true;
            context.Clients.Group(who).refereshDataFromSockets(triggerRefreshRequest);
        }
Example #14
0
        // Get: /Manage/ImportCalendar
        public async Task <ActionResult> ImportCalendar()
        {
            string    userID = User.Identity.GetUserId();
            TilerUser myUser = UserManager.FindById(User.Identity.GetUserId());
            dynamic   model  = new ExpandoObject();

            model.thirdpartyCalendars = (await dbContext.ThirdPartyAuthentication.Include(o => o.DefaultLocation).Where(obj => userID == obj.TilerID).ToListAsync()).Select(obj => obj.getThirdPartyOut());
            model.user = myUser;
            return(View(model));
        }
Example #15
0
        //
        // GET: /Manage/ChangeStartOfDay
        public ActionResult ChangeStartOfDay()
        {
            TilerUser myUser       = UserManager.FindById(User.Identity.GetUserId());
            long      Milliseconds = (long)(myUser.EndfOfDay.AddDays(10) - TilerElementExtension.JSStartTime).TotalMilliseconds;
            var       model        = new ChangeStartOfDayModel
            {
                TimeOfDay = Milliseconds.ToString()
            };

            return(View(model));
        }
Example #16
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            TilerUser tilerUser = null;

            using (AccountController accountController = new AccountController())
            {
                var userStore = new UserStore <TilerUser>(accountController.DbContext);
                ApplicationUserManager   applicationUserManager = new ApplicationUserManager(userStore);
                ApplicationSignInManager signInManager          = new ApplicationSignInManager(applicationUserManager, context.OwinContext.Authentication);
                var signInStatus = await signInManager.PasswordSignInAsync(context.UserName, context.Password, true, true).ConfigureAwait(false);

                switch (signInStatus)
                {
                case SignInStatus.Success:
                {
                    context.SetError("Success", "User login successfull.");
                    tilerUser = accountController.DbContext.Users.SingleOrDefault(user => user.UserName == context.UserName);
                }
                break;

                case SignInStatus.LockedOut:
                {
                    context.SetError("user_locked_out", "The user is locked out.");
                    return;
                }

                case SignInStatus.RequiresVerification:
                {
                    context.SetError("user_verification_requiried", "User has not verified account. User needs to check email for verification steps");
                    return;
                }

                case SignInStatus.Failure:
                default:
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            if (tilerUser != null)
            {
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, tilerUser.Id));
            }
            context.Validated(identity);
        }
Example #17
0
 async virtual public Task <UserAccount> getUserAccount(TilerDbContext db = null)
 {
     if (db != null)
     {
         return(new UserAccountDirect(UserID, db));
     }
     else
     {
         TilerUser User = new TilerUser()
         {
             UserName = UserName, Id = UserID
         };
         return(new UserAccountXml(User));
     }
 }
Example #18
0
 public DB_ProcrastinateAllSubCalendarEvent(TilerUser user, TilerUserGroup group, string timeZone, TimeLine timeLine, EventID calendarEventId, TilerElements.Location location, ProcrastinateCalendarEvent calendarEvent, bool isEnabled, bool isCompleted) : base(user, group, timeZone, timeLine, calendarEventId, location, calendarEvent)
 {
     this._TimeZone = timeZone;
     updateStartTime(timeLine.Start);
     updateEndTime(timeLine.End);
     this._RigidSchedule            = true;
     this.UniqueID                  = calendarEventId;
     this._Creator                  = user;
     this._Users                    = group;
     this._Enabled                  = isEnabled;
     this._Complete                 = isCompleted;
     this._ProfileOfNow             = new NowProfile();
     this._ProfileOfProcrastination = new Procrastination(new DateTimeOffset(), new TimeSpan());
     _isProcrastinateEvent          = true;
     this._calendarEvent            = calendarEvent;
 }
Example #19
0
        /// <summary>
        /// Essentially initializes the user log and pulls a user's account
        /// </summary>
        /// <returns></returns>
        public override async System.Threading.Tasks.Task <bool> Login()
        {
            HttpContext ctx       = HttpContext.Current;
            TilerUser   tilerUser = Database.Users
                                    .Include(eachUser => eachUser.ScheduleProfile_DB.PausedTile_DB)
                                    .SingleOrDefault(eachUser => eachUser.Id == ID);

            if (tilerUser != null && tilerUser.ScheduleProfile == null)
            {
                tilerUser.initializeScheduleProfile();
            }
            UserLog = new LogControlDirect(tilerUser, Database as ApplicationDbContext);

            bool retValue = tilerUser != null;

            return(retValue);
        }
Example #20
0
        public virtual async Task UpdateScheduleDueToExternalChanges()
        {
            TimeLine      newSubeEvent  = new TimeLine(Now.constNow, Now.constNow.AddMinutes(5));
            TimeSpan      fiveMinSpan   = new TimeSpan(1);
            EventName     tempEventName = new EventName(null, null, "TempEvent");
            TilerUser     user          = this.TilerUser;
            CalendarEvent TempEvent     = new CalendarEvent(
                tempEventName, newSubeEvent.Start, newSubeEvent.End, fiveMinSpan, new TimeSpan(), new TimeSpan(), 1, new Repetition(), new Location(), new EventDisplay(), new MiscData(), null, new NowProfile(), true, false, user, new TilerUserGroup(), user.TimeZone, null, null);

            tempEventName.Creator_EventDB = TempEvent.getCreator;
            tempEventName.AssociatedEvent = TempEvent;
            await AddToSchedule(TempEvent).ConfigureAwait(false);

            removeFromAllEventDictionary(TempEvent.Calendar_EventID.getCalendarEventComponent());
            removeFromAllEventDictionary(TempEvent.Calendar_EventID.ToString());
            await WriteFullScheduleToLog().ConfigureAwait(false);

            return;
        }
Example #21
0
        /*
         * // GET api/User/5
         * [NonAction]
         * [ResponseType(typeof(TilerUser))]
         * public async Task<IHttpActionResult> GetUser(string id)
         * {
         *  TilerUser user = await db.Users.SingleAsync(obj => obj.UserID == id); //.Asy(id); //await db.Users.Where(obj=>obj.UserID.FindAsync(id);
         *  if (user == null)
         *  {
         *      return NotFound();
         *  }
         *
         *  return Ok(user);
         * }
         */


        async public Task <TilerUser> GetUser(string ID, string userName)
        {
            List <TilerUser> AllUsers = await db.Users.Where(obj => obj.Id == ID).ToListAsync();

            TilerUser user = null;

            if (AllUsers.Count > 0)
            {
                if (user != null)
                {
                    if (user.UserName.ToLower() != userName.ToLower())
                    {
                        user = null;
                    }
                }
                user = AllUsers[0];
            }
            return(user);
        }
Example #22
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            ThirdPartyCalendarAuthenticationModelsController thirdPartyController = new ThirdPartyCalendarAuthenticationModelsController();

            thirdPartyController.initializeCurrentURI(System.Web.HttpContext.Current.Request.Url.Authority);
            if (ModelState.IsValid)
            {
                int            Min         = Convert.ToInt32(model.TimeZoneOffSet);
                TimeSpan       OffSet      = TimeSpan.FromMinutes(Min);
                DateTimeOffset EndOfDay    = new DateTimeOffset(2014, 1, 1, 22, 0, 0, OffSet);
                var            travelCache = new TravelCache();
                var            user        = new TilerUser {
                    UserName = model.Username, Email = model.Email, FirstName = model.FirstName ?? "", LastName = model.LastName ?? "", EndfOfDay = EndOfDay.UtcDateTime, TravelCache = travelCache
                };
                travelCache.Id = user.Id;
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    user = dbContext.Users.Find(user.Id);
                    await createProcrastinateCalendarEvent(user).ConfigureAwait(false);
                    await createAnalysis(user).ConfigureAwait(false);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    Task SendEmail = SendEmailConfirmationAsync(user.Id, "Please Confirm Your Tiler Account!");
                    await SendEmail.ConfigureAwait(false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    //return RedirectToAction("Index", "Home");
                    return(RedirectToAction("Desktop", "Account"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #23
0
        virtual protected async Task triggerNewlyAddedThirdparty()
        {
            if (retrievedThirdParty)
            {
                TimeLine      newSubeEvent  = new TimeLine(Now.constNow, Now.constNow.AddMinutes(5));
                TimeSpan      fiveMinSpan   = new TimeSpan(1);
                EventName     tempEventName = new EventName(null, null, "TempEvent");
                TilerUser     user          = TilerUser;
                CalendarEvent TempEvent     = new CalendarEvent(
                    tempEventName, newSubeEvent.Start, newSubeEvent.End, fiveMinSpan, new TimeSpan(), new TimeSpan(), 1, new Repetition(), new Location(), new EventDisplay(), new MiscData(), null, new NowProfile(), true, false, user, new TilerUserGroup(), user.TimeZone, null, null);
                tempEventName.Creator_EventDB = TempEvent.getCreator;
                tempEventName.AssociatedEvent = TempEvent;
                await AddToSchedule(TempEvent).ConfigureAwait(false);

                removeFromAllEventDictionary(TempEvent.Calendar_EventID.getCalendarEventComponent());
                removeFromAllEventDictionary(TempEvent.Calendar_EventID.ToString());
                return;
            }

            throw new Exception("Hey you are yet to retrieve the latest third party schedule");
        }
Example #24
0
        public async Task <TilerUser> forceLogin()
        {
            TilerUser retValue = null;


            if (_TilerUser != null)
            {
                HttpContext            myContext   = HttpContext.Current;
                ApplicationUserManager UserManager = myContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
                try
                {
                    retValue = await UserManager.FindByIdAsync(_TilerUser.Id).ConfigureAwait(false);

                    forcedLogin = true;
                }
                catch (Exception e)
                {
                    ;
                }
            }
            return(retValue);
        }
Example #25
0
        public async Task <IHttpActionResult> UpdateDefaultCalEventLocation([FromBody] CalendarDefaultLocation defaultLocation)
        {
            var thirdPartyLocation = await db.ThirdPartyAuthentication
                                     .Include(eachThirdPartyAuthentication => eachThirdPartyAuthentication.DefaultLocation)
                                     .Where((eachThirdPartyAuthentication) => eachThirdPartyAuthentication.ID == defaultLocation.Id)
                                     .SingleAsync().ConfigureAwait(false);


            string    userId    = User.Identity.GetUserId();
            TilerUser tilerUser = db.Users.Find(userId);

            if (thirdPartyLocation != null && tilerUser != null)
            {
                var LocationObj = defaultLocation.toLocation();
                LocationObj.User        = tilerUser;
                LocationObj.Description = "cal-default-location-" + Guid.NewGuid().ToString();
                Location retrievedDefaultLocation = null;
                if (thirdPartyLocation.DefaultLocationId.isNot_NullEmptyOrWhiteSpace())
                {
                    retrievedDefaultLocation = thirdPartyLocation.DefaultLocation;
                    retrievedDefaultLocation.update(LocationObj);
                }
                else
                {
                    retrievedDefaultLocation = LocationObj;

                    thirdPartyLocation.DefaultLocation = retrievedDefaultLocation;
                }

                await db.SaveChangesAsync().ConfigureAwait(false);

                return(Ok(retrievedDefaultLocation));
            }

            return(Ok());
        }
Example #26
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl, ThirdPartyCalendarAuthenticationModel ThirdPartyCredentials = null)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Desktop", "Account"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                string[] nameArray = (info.ExternalIdentity.Name ?? "").Split(' ');
                string   LastName  = "";
                string   FirstName = "";
                string   OtherName = "";
                if (nameArray.Length > 0)
                {
                    FirstName = nameArray[0];
                    if (nameArray.Length > 1)
                    {
                        LastName = nameArray.Last();
                    }
                    if (nameArray.Length > 2)
                    {
                        for (var i = 1; i < nameArray.Length - 1; i++)
                        {
                            OtherName = nameArray[i];
                            if (i + 1 < nameArray.Length - 1)
                            {
                                OtherName += " ";
                            }
                        }
                    }
                }
                var user = new TilerUser {
                    UserName = model.Email, Email = model.Email, FirstName = FirstName, LastName = LastName, OtherName = OtherName, EndfOfDay = DateTime.Now
                };


                var result = await UserManager.CreateAsync(user);


                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        user = dbContext.Users.Find(user.Id);
                        await createProcrastinateCalendarEvent(user).ConfigureAwait(false);
                        await createAnalysis(user).ConfigureAwait(false);

                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        Task SendThirdPartyAuthentication = new Task(() => { });
                        if (ThirdPartyCredentials != null)
                        {
                            string Email = ThirdPartyCredentials.Email;
                            SendThirdPartyAuthentication = PopulateGoogleAuthentication(user.Id, ThirdPartyCredentials.Token, ThirdPartyCredentials.RefreshToken, Email, ThirdPartyCredentials.Deadline);;
                        }

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        /*string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                         * var callbackUrl = Url.Action("ConfirmEmail", "Account",new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                         * Task SendEmail =UserManager.SendEmailAsync(user.Id,"Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here </a>");
                         */

                        Task SendEmail = SendEmailConfirmationAsync(user.Id, "Please Confirm Your Tiler Account!");
                        await SendThirdPartyAuthentication.ConfigureAwait(false);

                        await SendEmail.ConfigureAwait(false);

                        return(RedirectToAction("Desktop", "Account"));
                    }
                }

                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View("ExternalLoginConfirmation", model));
        }
Example #27
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            if (System.Web.HttpContext.Current != null)// this helps save the reurn uri for notification
            {
                ThirdPartyCalendarAuthenticationModelsController thirdPartyController = new ThirdPartyCalendarAuthenticationModelsController();
                thirdPartyController.initializeCurrentURI(System.Web.HttpContext.Current.Request.Url.Authority);
            }
            string ThirdPartyType;
            var    result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false).ConfigureAwait(false);

            switch (result)
            {
            case SignInStatus.Success:
            {
                ThirdPartyType = loginInfo.ExternalIdentity.FindFirst("ThirdPartyType").Value;
                DateTimeOffset Now = DateTimeOffset.UtcNow;
                if (ThirdPartyType == TilerElements.ThirdPartyControl.CalendarTool.google.ToString())
                {
                    string RefreshToken = loginInfo.ExternalIdentity.FindFirst("RefreshToken").Value;
                    if (!string.IsNullOrEmpty(RefreshToken))
                    {
                        TilerUser AppUser = await UserManager.FindAsync(loginInfo.Login).ConfigureAwait(false);

                        string   Email       = loginInfo.Email;
                        string   AccessToken = loginInfo.ExternalIdentity.FindFirst("AccessToken").Value;
                        TimeSpan fiveMin     = new TimeSpan(0, -5, 0);
                        TimeSpan Duration    = TimeSpan.Parse(loginInfo.ExternalIdentity.FindFirst("ExpiryDuration").Value);
                        Duration = Duration.Add(fiveMin);
                        Now      = Now.Add(Duration);
                        await PopulateGoogleAuthentication(AppUser.Id, AccessToken, RefreshToken, Email, Now).ConfigureAwait(false);
                    }
                }


                return(RedirectToAction("Desktop", "Account"));
            }

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account

                ThirdPartyType = loginInfo.ExternalIdentity.FindFirst("ThirdPartyType").Value;
                ThirdPartyCalendarAuthenticationModel thirdPartyModel = null;
                DateTimeOffset Deadline = DateTimeOffset.UtcNow;
                if (ThirdPartyType == TilerElements.ThirdPartyControl.CalendarTool.google.ToString())
                {
                    string RefreshToken = loginInfo.ExternalIdentity.FindFirst("RefreshToken").Value;
                    if (!string.IsNullOrEmpty(RefreshToken))
                    {
                        TilerUser AppUser = await UserManager.FindAsync(loginInfo.Login).ConfigureAwait(false);

                        string   Email       = loginInfo.Email;
                        string   AccessToken = loginInfo.ExternalIdentity.FindFirst("AccessToken").Value;
                        TimeSpan fiveMin     = new TimeSpan(0, -5, 0);
                        TimeSpan Duration    = TimeSpan.Parse(loginInfo.ExternalIdentity.FindFirst("ExpiryDuration").Value);
                        Duration                     = Duration.Add(fiveMin);
                        Deadline                     = Deadline.Add(Duration);
                        thirdPartyModel              = new ThirdPartyCalendarAuthenticationModel();
                        thirdPartyModel.Deadline     = Deadline;
                        thirdPartyModel.Email        = Email;
                        thirdPartyModel.Token        = AccessToken;
                        thirdPartyModel.RefreshToken = RefreshToken;
                    }
                    else
                    {
                        string Email       = loginInfo.Email;
                        string AccessToken = loginInfo.ExternalIdentity.FindFirst("AccessToken").Value;
                        thirdPartyModel              = new ThirdPartyCalendarAuthenticationModel();
                        thirdPartyModel.Deadline     = Deadline;
                        thirdPartyModel.Email        = Email;
                        thirdPartyModel.Token        = AccessToken;
                        thirdPartyModel.RefreshToken = RefreshToken;
                        thirdPartyModel.ID           = Email;
                        await thirdPartyModel.revokeAccess().ConfigureAwait(false);
                    }
                }

                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                if (string.IsNullOrEmpty(loginInfo.Email))
                {
                    return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                        Email = loginInfo.Email
                    }));
                }
                else
                {
                    return(await ExternalLoginConfirmation(new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }, returnUrl, thirdPartyModel));
                }

                //return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
            }
        }
Example #28
0
        public async Task <ActionResult> RegisterUser(RegisterViewModel model)
        {
            ThirdPartyCalendarAuthenticationModelsController thirdPartyController = new ThirdPartyCalendarAuthenticationModelsController();

            thirdPartyController.initializeCurrentURI(System.Web.HttpContext.Current.Request.Url.Authority);
            PostBackData retPost  = new PostBackData("Failed to register user", 3);
            JsonResult   RetValue = new JsonResult();

            if (ModelState.IsValid)
            {
                int            Min         = Convert.ToInt32(model.TimeZoneOffSet);
                TimeSpan       OffSet      = TimeSpan.FromMinutes(Min);
                DateTimeOffset EndOfDay    = new DateTimeOffset(2014, 1, 1, 22, 0, 0, OffSet);
                var            travelCache = new TravelCache();
                var            user        = new TilerUser {
                    UserName = model.Username, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, EndfOfDay = EndOfDay.UtcDateTime, TravelCache = travelCache
                };
                travelCache.Id = user.Id;

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    user = dbContext.Users.Find(user.Id);
                    await createProcrastinateCalendarEvent(user).ConfigureAwait(false);
                    await createAnalysis(user).ConfigureAwait(false);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    Task SendEmail = SendEmailConfirmationAsync(user.Id, "Please Confirm Your Tiler Account!");
                    await SendEmail.ConfigureAwait(false);

                    string LoopBackUrl = "";
                    if (Request.Browser.IsMobileDevice)
                    {
                        LoopBackUrl = "/Account/Mobile";
                    }
                    else
                    {
                        LoopBackUrl = "/Account/Desktop";
                    }

                    retPost       = new PostBackData(LoopBackUrl, 0);
                    RetValue.Data = (retPost.getPostBack);
                    return(RetValue);


                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                }
                retPost       = new PostBackData(string.Join("<br>", result.Errors.Select(obj => obj.Split('.')).SelectMany(obj => obj)), 3);
                RetValue.Data = (retPost.getPostBack);
                return(RetValue);
            }
            string AllErrors = string.Join("<br>", ModelState.Values.SelectMany(obj => obj.Errors.Select(obj1 => obj1.ErrorMessage)));

            retPost       = new PostBackData(AllErrors, 3);
            RetValue.Data = (retPost.getPostBack);

            return(RetValue);
        }
Example #29
0
 /*
  * public LogControlDebug(string userid)
  * {
  *  UserID = userid;
  * }
  */
 public LogControlXml(TilerUser User, string logLocation = "") : base(User, null)
 {
 }
Example #30
0
 public UserAccountXml(TilerUser user)
 {
     UserLog = new LogControlXml(user, "");
     ID      = SessionUser.Id;
 }