Flask db.Column(db.Boolean) not updating for email confirmation - sqlite

i am trying to update a db column but it's not working for some reason, the boolean value is not changing to True. in database it is always False even when i confirm the email try token.
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer(),primary_key=True)
name = db.Column(db.String)
email = db.Column(db.String)
password = db.Column(db.Integer)
date_added = db.Column(db.DateTime)
confirmed_email = db.Column(db.Boolean, nullable=True, default=False)
def __init__(self,name,email,password,date_added):
self.name = name
self.email = email
self.password = password
self.date_added = date_added
and this is my route for token
#app.route('/confirm_email/<token>')
def confirm_email(token):
try:
email = serializer.loads(token, salt='true', max_age=250)
except SignatureExpired:
return 'The token is expired for'
user = User.query.filter_by(email=email).first()
user.confirmed_email = True
db.session.add(user) #<-- i tried also without this line
db.session.commit()
return redirect(url_for('index'))

Related

How to retrieve user object using PostMan to test my endpoints

Users can create and maintain their profiles rather than enter in
their information each time they order
API Actions:
Retrieve a User Object and its fields by their username
Update the user and any of their fields except for mail
This is my code below:
views.py
"""api views inlcude method: customer list, """
#csrf allows for post without auth
#csrf_exempt
def List_All_Customers(request):
customer = Customer.objects.all()
#returns all the customer from db
if request.method == 'GET':
serializer = CustomerSerializer(customer, many=True)
return JsonResponse(serializer.data, status= 200, safe=False)
#add new customer in the db
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = CustomerSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
#csrf_exempt
def Customer_detail(customer):
#check if the customer with the given name is in the database
try:
customer = Customer.objects.filter(name = name)
#if not in database, throw 400 error
except Customer.DoesNotExist:
return HttpResponse(status = 404)
#if customer exists with the given name and is a get method, return that name object
if request.method == 'GET':
serializer = CustomerSerializer(customer)
return JsonResponse(serializer.data)
#delete method will delete the customer with a specific name
elif request.method == 'DELETE':
Customer.objects.filter(name = name).delete()
return HttpResponse(status=204)
#csrf_exempt
def get_current_user(request):
if request.method == 'POST':
customer = request.POST.get('name')
customer = authenticate(user=user)
if customer:
if customer.is_authenticated:
signBool = signatureAuth(username)
if signBool == 'AUTHENTICATED':
login(request, customer, backend=settings.AUTHENTICATION_BACKEND[0])
return JsonResponse(serializer.data)
'''
return JsonResponse({
'user':customer.user,
'name':customer.name,
'email':customer.email,
})
'''
model.py
class Customer(models.Model):
user=models.CharField(max_length=200,null=True)
name=models.CharField(max_length=200,null=True)
email=models.CharField(max_length=200,null=True)
password=models.CharField(max_length=200,null=True)
card_info=models.CharField(max_length=200,null=True)
def __str__(self):
return str(self.Customer)

I am not able to add form entries to my database

Problem
I am trying to push username and password entries to my database using following code(named as application.py inside my project)
Code
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
application = Flask(__name__)
application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydtb.db'
db = SQLAlchemy(application)
class Mydtb(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement = True)
user = db.Column(db.String(50), nullable = False)
password = db.Column(db.String(20), nullable = False)
created = db.Column(db.DateTime, default = datetime.utcnow)
def __init__(self, user, password):
user = self.user
password = self.password
#application.route('/', methods=['POST', 'GET'])
def home():
title = 'Registration page'
if request.method == 'POST':
record = Mydtb(request.form['usrname'], request.form['pwd'])
db.session.add(record)
db.session.commit()
return redirect('/')
else:
mydtb = Mydtb.query.order_by(Mydtb.created)
return render_template('index.html', title=title, mydtb = mydtb)
if __name__ == '__main__':
application.run(debug = True)
I've already generated .db file, html form is also working fine but it seems application.py code is unable to push those form entries to database.
You can see the error that I am getting from debug section , I want to fix it without using extra libraries.

Flask Bcrypt TypeError: initializer for ctype 'char *' must be a cdata pointer, not NoneType

Encountered this bug. Being an amateur coder I'm really struggling to figure out what I'm doing wrong.
File "C:\Users.virtualenvs\flask\lib\site-packages\bcrypt__init__.py", line 63, in hashpw
retval = _bcrypt.lib.crypt_rn(password, salt, hashed, len(hashed))
TypeError: initializer for ctype 'char *' must be a cdata pointer, not NoneType
Models.py
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password = db.Column(db.String(100))
posts = db.relationship('Post', backref='author', lazy='dynamic',
primaryjoin="User.id==Post.user_id")
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime)
followed = db.relationship('User',
secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'),
lazy='dynamic')
#reviews = db.relationship('Review', backref='author', lazy='dynamic') This is the review connectino for the user.
#hybrid_property
def password_hash(self):
return self.password
#password_hash.setter
def set_password(self, plaintext):
self.password = bcrypt.generate_password_hash(plaintext)
def is_correct_password(self, plaintext):
return bcrypt.check_password_hash(self.password, plaintext)
Views.py
#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(nickname=form.nickname.data).first_or_404()
if user.is_correct_password(form.password.data):
login_user(user)
flash("you've been logged in!, 'success'")
return redirect(url_for('index'))
else:
flash('your email or password doesnt match!', 'error')
return redirect(url_for('login'))
return render_template('login.html',
title='Sign In',
form=form)

Allowing the attacker to access unathorized records finding

I have a scan finding and hope someone can provide any ideas as to best ways to resolve the issue. First I will show the scan Finding then my code and finally what the scanner's recommended solution is.
Finding
Without proper access control, the method GetAttributeKey() in Provider.cs can execute a SQL statement on line 163 that contains an attacker-controlled primary key, thereby allowing the attacker to access unauthorized records.
Rather than relying on the presentation layer to restrict values submitted by the user, access control should be handled by the application and database layers. Under no circumstances should a user be allowed to retrieve or modify a row in the database without the appropriate permissions. Every query that accesses the database should enforce this policy, which can often be accomplished by simply including the current authenticated username as part of the query.
My Code:
Offending line:
myParam.SqlParam.Value = attribute;
Method:
public string GetAttributeKey(string attribute)
{
string qry = "SELECT ws_attribute_key FROM webservice_attributes WHERE ws_attribute = #attribute";
QueryContainer Instance = new QueryContainer(qry);
MyParam myParam = new MyParam();
myParam.SqlParam = new SqlParameter("#attribute", Instance.AddParameterType(_DbTypes._string));
myParam.SqlParam.Value = attribute;
Instance.parameterList.Add(myParam);
object key = ExecuteScaler(Instance);
return Convert.ToString(key);
}
Scanner's Recommend fix:
string user = ctx.getAuthenticatedUserName();
int16 id = System.Convert.ToInt16(invoiceID.Text);
SqlCommand query = new SqlCommand(
"SELECT * FROM invoices WHERE id = #id AND user = #user", conn);
query.Parameters.AddWithValue("#id", id);
query.Parameters.AddWithValue("#user", user);
SqlDataReader objReader = query.ExecuteReader();
I think the problem is dealing with the code calling the GetAttributeKey. The method is called only if the user has no access to to the Attribute. I think I need some type of checking. Here is the calling code:
if (result.Rows.Count > 0)
{
// get the attribute
DataRow[] rows = result.Select("ws_attribute = '" + attribute + "'");
if (rows.Length > 0)
{
// check time range
string hr = DateTime.Now.Hour.ToString();
DataRow[] valid = result.Select("ws_attribute = '" + attribute + "' AND start_time <= " + hr + " AND end_time >= " + hr);
if (valid.Length > 0)
{
ws_user_attribute_key = Convert.ToInt32(valid[0]["ws_user_attribute_key"].ToString());
ret = true;
// generate salt
TextEncryptor te = new TextEncryptor();
salt = te.CreateSalt(8);
// save to the log, return false if failed to log
if (!LogTransfer(ipAddress, accessDate, fileName, ws_user_attribute_key, salt, out logKey))
return false;
}
else
{
ret = false;
LogInvalidAccess(username, rows[0]["ws_attribute_key"].ToString(), ipAddress, accessDate, WSInvalidAccessReason.OutsideValidTimeRange);
}
}
else
{
// if user has no access to attribute
ret = false;
LogInvalidAccess(username, GetAttributeKey(attribute), ipAddress, accessDate, WSInvalidAccessReason.AttributeNotAccessible);
}
}
else
{
ret = false;
LogInvalidAccess(username, GetAttributeKey(attribute), ipAddress, accessDate, WSInvalidAccessReason.InvalidAccount);
}

Updated Google Analytic API and older version

Before Google Analytic Update there api this code works.
string userName = GAEmailAddress.ToString();//Its From Database
string passWord = GAPassword.ToString();//Its From Database
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
AccountQuery query = new AccountQuery();
AnalyticsService service = new AnalyticsService("AnalyticsApp");
if (!string.IsNullOrEmpty(userName))
{
service.setUserCredentials(userName, passWord);
}
string str = "";
try
{
AccountFeed accountFeed = service.Query(query);
foreach (AccountEntry entry in accountFeed.Entries)
{
str = entry.ProfileId.Value;
}
DataQuery query1 = new DataQuery(dataFeedUrl);
// Bounce Rate Calculations
query1.Ids = str;
query1.Metrics = "ga:visits,ga:bounces";//visitors
query1.Sort = "ga:visits";
query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
query1.StartIndex = 1;
//Others code and other data for bound
I search in SO and and Find this link.
gapi account data url goes to 404
I replace this link :
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
with:
https://www.googleapis.com/analytics/v2.4/management/accounts?start-index=1&max-results=100&key=API_KEY
But I still I gett error:
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
I still search and find this link:
https://developers.google.com/analytics/devguides/reporting/core/v2/#register
As link says I replace :
https://www.googleapis.com/analytics/v2.4/data
But still I got error ? What I am missing here? Thanks.

Resources