class BlogPost(db.Model):
users = db.relationship(User)
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
Username= db.Column(db.Text)
Password = db.Column(db.LargeBinary(length=500),nullable=True)
Strength=db.Column(db.Text)
I have these columns in data base table and when I want to retrieve the data :
user = User.query.filter_by(username=current_user.username).first_or_404()
posts=BlogPost.query.filter_by(user_id=current_user.id).all()
When I try to access each value in posts for example post[0], the datatype shown is:
<class 'password.models.BlogPost'>
I am trying to make a password manager and I have encrypted the passwords before storing it into the database and by doing so it changes to base64(bytes) and hence I want it to retrieve it in the datatype in which it was stored,so that I can decrypt it, however when I Try decrypting it it says that token must be in bytes , can someone help me solve this issue.
I have another 'USER' table for storing user data, which is email,password,etc.
When you access post[0], you are accessing the entire post object. Try using post[0].password.
Related
I am a bit stuck here.
Using a very simple Shiro configuration with jdbcRealm:
[main]
cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager
# Create JDBC realm.
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
# Configure JDBC realm datasource.
ds = org.postgresql.ds.PGSimpleDataSource
ds.databaseName = pg_sensor
***
jdbcRealm.dataSource = $ds
# Configure JDBC realm SQL queries.
jdbcRealm.authenticationQuery = SELECT pass FROM users WHERE name = ?
# user id is a user Role )
jdbcRealm.userRolesQuery = SELECT id FROM users WHERE name = ?
So, I use userid as a role to do authorization in the code.
In one scenario I need to get role name to proceed.
Can anyone suggest how to do that from the Principal (SecurityUtils.getSubject().getPrincipal())?
I guess we need to use getRoles() withing SimpleAccount class, but not able to connect it with Principal.
Before anything, some comment about your shiro.ini:
Role query
First of all, your jdbcRealm.userRolesQuery does not really make sense: you are supposed to fetch the roles not the users for this query.
Assuming you have tables
CREATE TABLE user{
id INTEGER,
username VARCHAR,
password VARCHAR
}
CREATE TABLE user_role{
id INTEGER,
role_name VARCHAR,
username VARCHAR
}
your queries would like:
# Configure JDBC realm SQL queries.
jdbcRealm.authenticationQuery = SELECT password FROM user WHERE username = ?
# user id is a user Role )
jdbcRealm.userRolesQuery = SELECT role_name FROM user_role WHERE username = ?
Principal
I'm assuming that your subject is already successfully authenticated. So far, SecurityUtils.getSubject().getPrincipal() will only return the login or username, anything which identify your user but nothing more. In my above example, it would return the value stored in username column.
Role check
I think, you are rather looking does this authenticated user has role "MyRole"?. In this case, you can have a look around SecurityUtils.getSubject().hasRole("MyRole"). As far as I know, there is no way to list all the roles a subject currently has. You can only check if the subject has such or such role
Feel free to comment if I misunderstood your question
I am attempting to model a friendship using SQLAlchemy ORM. The relationship that I am trying to model is symmetric. Similar to Facebook, if user a is to add user b, user b must approve that friendship request. My current model is as follows.
class User(db.Model):
__tablename__ = 'User'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(35), unique=False)
username = db.Column(db.String(25), index=True, unique=True)
password = db.Column(db.String(35), unique=False)
email = db.Column(db.String(35), unique=True)
phone_number = db.Column(db.String(22))
# define relationships
requester = db.relationship('Relationship', foreign_keys='Relationship.requesting_user', backref='requester')
receiver = db.relationship('Relationship', foreign_keys='Relationship.receiving_user', backref='received')
def __repr__(self):
return '<User %r>' % (self.username)
class Relationship(db.Model):
__tablename__ = 'Relationship'
id = db.Column(db.Integer, primary_key=True)
requesting_user = db.Column(db.Integer, db.ForeignKey('User.id'))
receiving_user = db.Column(db.Integer, db.ForeignKey("User.id"))
status = db.Column(db.Integer)
__table_args__ = (db.UniqueConstraint('receiving_user', 'requesting_user', name='_receiving_user_uc'), )
The model works, however, I don't think that it is properly modeled. Is it even required that I use a status? I'm assuming it can be modeled so that each friend relationship gets its own entry. Currently, a user can initiate a friend request with another user. When the other user approves the request, the status changes to accepted. I have looked a little into association tables but am not too sure how they would play into a model like this. Any advice on my current model and how it can be improved would be greatly appreciated.
Among other things, you may want to learn about association proxies. An association proxy tells SQLAlchemy that you have a many-to-many relationship mediated by an intermediate table which may contain additional data. In your case, each User can send multiple requests and also receive multiple requests and Relationship is the mediating table which contains the status column as additional data.
Here is a variant of your code which stays relatively close to what you wrote:
from sqlalchemy.ext.associationproxy import association_proxy
class User(db.Model):
__tablename__ = 'User'
# The above is not necessary. If omitted, __tablename__ will be
# automatically inferred to be 'user', which is fine.
# (It is necessary if you have a __table_args__, though.)
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(35), unique=False)
# and so forth
requested_rels = db.relationship(
'Relationship',
foreign_keys='Relationship.requesting_user_id',
backref='requesting_user'
)
received_rels = db.relationship(
'Relationship',
foreign_keys='Relationship.receiving_user_id',
backref='receiving_user'
)
aspiring_friends = association_proxy('received_rels', 'requesting_user')
desired_friends = association_proxy('requested_rels', 'receiving_user')
def __repr__(self):
# and so forth
class Relationship(db.Model):
# __tablename__ removed, becomes 'relationship'
# __table_args__ removed, see below
requesting_user_id = db.Column(db.Integer, db.ForeignKey('User.id'), primary_key=True)
receiving_user_id = db.Column(db.Integer, db.ForeignKey('User.id'), primary_key=True)
# Marking both columns above as primary_key creates a compound primary
# key, which at the same time saves you the effort of defining the
# UNIQUE constraint in __table_args__
status = db.Column(db.Integer)
# Implicit one-to-many relations: requesting_user, receiving_user.
# Normally it would be more convenient to define those relations on
# this side, but since you have two outgoing relationships with the
# same table (User), you chose wisely to define them there.
(Note how I ordered the lines slightly differently and how I used the _id suffix for foreign key columns while reserving the same name without the suffix for the corresponding db.relationships. I would suggest that you adopt this style, too.)
Now you have a clean way to access incoming and outgoing friendship requests as well as the corresponding users directly from your User model. However, this is still less than ideal because you need to write the following code in order to get all confirmed friends of a user:
def get_friends(user):
requested_friends = (
db.session.query(Relationship.receiving_user)
.filter(Relationship.requesting_user == user)
.filter(Relationship.status == CONFIRMED)
)
received_friends = (
db.session.query(Relationship.requesting_user)
.filter(Relationship.receiving_user == user)
.filter(Relationship.status == CONFIRMED)
)
return requested_friends.union(received_friends).all()
(I did not test this; you might need to also join with User in both queries in order for the union to work.)
To make things worse, the model name Relationship as well as the names of several members within the models don't seem to convey very well what they actually mean.
You can improve matters by removing Relationship.status and renaming Relationship to FriendshipRequest. Then, add a second User-to-User association model called Friendship and add a corresponding second set of db.Relationships with backrefs and association_proxys to User. When somebody sends a friendship request, you file a record to FriendshipRequest. If the request is accepted, you remove the record and replace it with a new record in Friendship. This way, instead of using a status code, the status of a friendship is encoded by the table in which you store a pair of users. The Friendship model may look like this:
class Friendship(db.Model):
user1_id = db.Column(db.Integer, db.ForeignKey('User.id'), primary_key=True)
user2_id = db.Column(db.Integer, db.ForeignKey('User.id'), primary_key=True)
# Implicit one-to-many relations: user1, user2
# (defined as backrefs in User.)
(Corresponding db.relationships and association_proxys in User are left as an exercise to the reader.)
This approach saves you half of the filtering operations when you need the confirmed friends of a user. Still, you need to make a union of two queries because your user can be either user1 or user2 in each instance of Friendship. This is inherently difficult because we are dealing with a reflexive symmetric relationship. I think it is possible to invent still more elegant ways to do it, but I think that would be complicated enough to warrant a new question here on Stack Overflow.
I have a domain class UserProfile which has one to one relationship with another domain class User.The Structure of the domain is provided.
сlass UserProfile {
String fio
String position
String phone
String email
static belongsTo = [user: User]
static constraints = {
// some constraints
}
static mapping = {
//some mapping; user property is not mapped
}
I need to write a native sql query in Grails for UserProfile domain and I don't know how to refer to user property(static belongsTo = [user: User]). I have tried USER_ID but it is not working.
I can't name the column directly using mapping section; I just need to find out how user column in UserProfile domain is named in database and how it can be called in native sql query.
Very Simple if i got your question ,Grails gorm convention for storing fileds in data base is:
Like
user_profile for UserProfile -Domain
and all fileds are speparedted by underscores and most of the time gorm adds _id after a foreign key reference /or a GORM relationship like above One to One and one to Many
[belongsTo=[user]] .
Inside SQL Table
mysql describe user_profile ;
----------------------------------------------------------------
User_Profile
----------------------------------------------------------------
id
version
foo varchar(50)
postion
email
user_instance_id int
-------------------------------------------------------------------
NATIVE SQL QUERY WILL BE :
'select up.user_instance_id from user_profile as up '
the Get all the userInstance objects by querying the user table
'select * from user where user.id = 'the id you get it from the above query'
I hope you have some idea on this please ,if i didnt get it let me know.
I believe if you define user inside UserProfile, then you can access it and will automatically be mapped? It works in my previous projects, I hope it will work with this.
сlass UserProfile {
String fio
String position
String phone
String email
static belongsTo = [user: User]
User userInstance;
static constraints = {
// some constraints
}
Then you can use it
UserProfile.executeQuery("select up.userInstance from UserProfile up")
In one application I need to create two types of accounts, let's say users and tutors.
Each of them should be able to register/login/... user/tutor account defined by different tables in db.
e.g.
[app]/user/register should provide a form with fields: username, email, password, hobby
[app]/tutor/register should provide a form with fields: username, email, pass, name, surname, telephone
Web2py auth service allows using auth_user table which can be customized. Is there a way to use two tables separately according to controller in one application?
Field auth.settings.table_user contains reference for auth_table but I probably shouldn't use it for this purpose.
The Auth system isn't designed to work this way. Instead, it would probably be better to put all the fields for both user types in the single auth_user table and then selectively set the readable and writable attributes of the fields to True or False depending on the context.
In the model file defining Auth:
user_extra_fields = [Field('hobby'), ...]
tutor_extra_fields = [Field('telephone', ...]
auth.settings.extra_fields['auth_user'] = (
[Field('user_type', requires=IS_IN_SET(['User', 'Tutor']))] +
user_extra_fields + tutor_extra_fields)
In the controller that manages the Auth functions:
def user():
if request.args(0) in ['register', 'profile']:
hidden_fields = (user_extra_fields if request.args(1) == 'tutor'
else tutor_extra_fields)
for field in hidden_fields:
field.readable = field.writable = False
return dict(form=auth())
I have a site where user A can book a lesson with a teacher, I then want to have an email sent to the teachers saying user A wants to book a lesson with you etc.
I have postal up and running sending emails without issue,
however, I don't know how to access the email address of the teacher to send the email.
The email address is saved as part of the built in UserProfile table. I have the teacher's UserId (as it's stored in a separate teacher table).
So is there a way to access the teachers email ,searching by UserId?
In any other table I would use t in db.Teacher.find(id) but this doesn't work within the Account Controller.
This was built using the default MVC4 internet website template using the built in simple membership. Let me know if more information is needed.
I've added the following to the AccountController;
private UsersContext db = new UsersContext();
public ActionResult EmailNotification(int id)
{
var user = from l in db.UserProfiles.Find(id)
select l;
}
db.UserProfiles.Find(id) however gives the following error;
Could not find an implementation of the query pattern for source type 'LessonUp.Models.UserProfile'. 'Select' not found.
Which I assume is a result of it not being created through the entity framework?
I think your query needs to be something like the following:
var result = from q in context.UserProfiles
where q.UserId == id
select q;