Sessions in Swift - xcode

If I have a logged in user and stored his id inside the app using
NSUserDefaults.standardUserDefaults().setBool(true, forKey:"isUserLoggedIn");
NSUserDefaults.standardUserDefaults().synchronize();
How can make it as a session so I can use it in every page
example Welcome "userLoggedin"

use singleton maybe helpful:
class LoginInfo {
var isLogin:Bool = false
static let shareInstance = LoginInfo()
init() {}
}
// when login success set isLogin be true
LoginInfo.shareInstance.isLogin = true
// when login out set isLogin be false
LoginInfo.shareInstance.isLogin = false
// in other pages can call this
if LoginInfo.shareInstance.isLogin {
// do something
}
hope it be helpful :-)

For you store the id user, you use:
NSUserDefaults.standardUserDefaults().setObject(userId, forKey:"userId");
NSUserDefaults.standardUserDefaults().synchronize();
In other page:
let userId = NSUserDefaults.standardUserDefaults().objectForKey("userId") as? [String]

Related

Opening and using a database from another view controller

I have created a database in one view controller and I would like to open it and access it in another view controller. I was wondering how to open up a existing database from one view controller in another view controller. I intend to open up the database and be able to update a row, so I would also need access to the "parts" (ex. id, name, email). Could you help me? Anything would be helpful. Thanks!
You can access your DB from any VC. Code (which you will probably use anywhere you want to access your DB from) would be like
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
do {
let db = try Connection("\(path)/<your.db.filename>")
let recordsTable = Table("records")
//or whatever you'd like to do, extract, modify, insert or delete
}
catch let error {
print("Data operation failed for records table: \(error)")
}
Instead of copying same code all over your project, you can separately create your own class for any of your DB operations and access it from anywhere:
class DatabaseOps {
//..
func getHighscoreTable() -> Array<HighScoreDataArray> {
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
var highscores = [HighScoreDataArray]()
do {
let db = try Connection("\(path)/tasksolver.db")
let score = Expression<Int>("Score")
let username = Expression<String>("Username")
let recordsTable = Table("records").order(score.desc).limit(10)
for row in try db.prepare(recordsTable) {
let highscore = HighScoreDataArray(score: Int(row[score]), username: String(row[username]))
highscores += [highscore]
}
} catch let error {
print("Data operation failed for records table: \(error)")
}
return highscores
}
//..
}
class RecordsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myDb : DatabaseOps = DatabaseOps()
//...
super.viewDidLoad()
//get the data from database by using myDB method
myHighScoreTable = myDb.getHighscoreTable()
Also, before you try it in different VCs - don't forget to make sure you have your DB file in place. If it is not, let db = try Connection will create an empty database for you, which will not contain any of your data or tables you want to access.

Roles added to the user does give false in IsInRole

I am trying to use [Authorize(Roles = "Administrator")]
But I always get "Access denied".
To test if i added the roles correct i added the following code in my controller:
var test=User.IsInRole("Administrator");
var user = await userManager.GetUserAsync(User);
var roles =await userManager.GetRolesAsync(user);
rolesOfUser = roles.ToList();
Have I added the role wrong?
Why does IsInRole always return false? is suggesting that the user is not signin or completed all authentication process. If the is the case how do i do that?
Seeding data:
public async Task SeedAsync()
{
context.Database.EnsureCreated();
if (await roleManager.RoleExistsAsync("Administrator") == false)
{
await roleManager.CreateAsync(new IdentityRole("Administrator"));
}
var user = await userManager.FindByEmailAsync("Jakob.Madsen#********.com");
if (user == null)
{
user = new IdentityUser()
{
UserName = "Jakob.Madsen#*********.com",
PhoneNumber = "*********",
Email = "Jakob.Madsen#*********.com",
};
var result = await userManager.CreateAsync(user, "*********");
if (result == IdentityResult.Success)
{
userManager.AddToRoleAsync(user, "Administrator").Wait();
}
else
{
throw new InvalidOperationException("Could not create Administrator");
}
}
var resultRoles = await userManager.GetRolesAsync(user);
if (resultRoles.Contains("Administrator") == false)
{
userManager.AddToRoleAsync(user, "Administrator").Wait();
}
}
Update:
I follow this ASP .Net Core Identity Role Claims not adding to User as suggested.
And it now works.
The IsInRole method and [Authorize(Roles="Administrator")] attribute check whether an identity that this claims principal possesses contains a claim of type ClaimsIdentity.RoleClaimType(http://schemas.microsoft.com/ws/2008/06/identity/claims/role) where the value of the claim is equal to the value specified by the role parameter.
So to summarize, if you call IsInRole, by default the assumption is that your claims representing roles have the type mentioned above – otherwise the role check will not succeed. You can confirm that by listing the claims :
var claims = User.Claims.ToList();
You haven't provide how you seed the roles , but you can find a lot of code samples :
ASP.NET Core 2.0: Getting Started With Identity And Role Management
.NET Core 2.1 Use Role Management
Also don't forget to logout and login again to see the desired behavior .

nativescript - how set global variables

I'm starting with nativescript with latest version.
I've finished tutorial on offical page, but now i have more questions than answers.
Can anybody tell me, what strategies can i use to set some variables, for example after succesfull login, how to set variable or even better, run some function that is doing checks globally, and not on every view or model file ?
I see that app.js is starting point for app, but looks like it cannot do any global checks ?
I think, second question is related :
Almost every model view file (file called as {viewname}).js is using:
var frameModule = require('ui/frame');
Is there a way to declare this once ? Or i have to run this every time when i need frame methods ? Or maybe if this is possible, lead to poor perforance?
Thanks for any advices.
NativeScript has a global Variable Scope.
To use it add global. in front of a variable name:
global.userName = "usernameXYZ";
To call it:
console.log("Username= "+global.userName);
Thanks Nikolay. Im using this pattern (maybe will help somebody)
register JS:
var page = require ("ui/core/view");
var frameModule = require('ui/frame');
var appSettings = require('application-settings');
exports.loaded = function(args) {
page = args.object;
};
exports.register = function() {
var userName = page.getViewById('userName');
var userPass = page.getViewById('userPass');
if (userName.text != '' && userPass.text != '') {
var name = userName.text;
var pass = userPass.text;
appSettings.setString('name', name);
appSettings.setString('pass', pass);
appSettings.setBoolean('auth', true);
var topmost = frameModule.topmost();
var navigationEntry = {
moduleName: "main-page",
context: { info: "something you want to pass to your page" },
animated: true,
transition: "curlDown",
clearHistory: true
};
topmost.navigate(navigationEntry);
} else {
alert('Please, fill form');
}
};
i use model as a global like this, in model.js (or whatever you want to call it)
`
var viewModel=require("data/observable");
var model= new viewModel.Observable();
module.exports= model;`
Then say in your login.js
` const model=require('./model')
const password = //a password from page
const userName = //a name from page
//after some logic to verify credentials set them accordingly as below
model.password=password
model.userName=userName
`
now if say you are navigated to home.js or any page for that matter, just call it whenever required like so const pass=model.password,name=model.userName all with courtesy from 'model.js'

Specifying LUIS dialog spellCheck, slot programmatically

so far I was able to avoid hardcoding my LUIS appId and key by doing the following:
var luisService = new LuisService(new LuisModelAttribute(ConfigurationManager.AppSettings["LuisAppId"], ConfigurationManager.AppSettings["LuisAppKey"]));
context.Call(new LuisDialog(luisService), ResumeAfterDialog);
And then having my LUIS dialog declared as:
[Serializable]
public class LuisDialog : LuisDialog<object>
{
public LuisDialog(ILuisService ls) : base(ls)
{
}
....
}
}
But I would also like to be able to set SpellCheck=true, Log, Verbose and other parameters available in the LuisModel attribute programmatically, is there a way of doing that?
Thanks
I figured it out, I just need to set the LuisModelAttribute properties in code before creating the LuisService:
var luisSettings = new LuisModelAttribute(ConfigurationManager.AppSettings["LuisAppId"], ConfigurationManager.AppSettings["LuisAppKey"]);
luisSettings.Log = true;
luisSettings.SpellCheck = true;
luisSettings.Log = true;
var luisService = new LuisService(luisSettings);
context.Call(new LuisDialog(luisService), ResumeAfterDialog);

How can I see which Pages a User requests in Grails?

I use the Grails Application Info Plugin to get active sessions as:
ScopesInfoService scopesInfoService
List<Map<String, Object>> activeSessionsMap = scopesInfoService.getSessionsInfo()
activeSessionsMap.each { sessionMap ->
def tmpSession = sessionMap.session
}
How can I see which page a user with a session has been requested and is requesting?
Create a filter and store the current controller and action or request.forwardURI for each request in a variable called currentLocation or something. When you access sessions just read that. you can be creative with it and store any data. but not sure this is a proper approach anyway.
storeLocation(controller: '*', action: '*') {
before = {
session.currentLocation = "$controllerName/$actionName"
}
}
This plugin will not give you that. You need to develop something yourself.
You can create a grails Filter that saves to your database (create a new table for this) the information about the session, user and about the URI (your pages) is being requested.
Sample filter:
class UserInfoFilters {
def filters = {
all(controller:'*', action:'*') {
before = {
SessionUserInfoDomainClass s = new SessionUserInfoDomainClass()
// populate your domain class above with the info you need. Examples:
s.user = session.user
s.controller = controllerName
s.save()
}
}
}
}
Then you can easily have some UI (even with scaffolg) of this SessionUserInfoDomainClass to read the info you want.

Resources