Enter in MUC room with another username - ejabberd

When im trying to enter in a room with another username then i entered in room with a different username.
Like
my username is admin and when i send this xml to enter in room
<presence to="roomname#conference.server.com/fakeuser" type="available"/>
then 'admin' will enter in room with 'fakename'
how to disallow this to all users so, they will enter in room with real names only.

This patch blocks presence stanzas with nickname different than username, and returns an error to the user:
diff --git a/src/mod_muc_room.erl b/src/mod_muc_room.erl
index 492f9a4b3..3918401d1 100644
--- a/src/mod_muc_room.erl
+++ b/src/mod_muc_room.erl
## -342,6 +342,15 ## normal_state({route, <<"">>, #iq{} = IQ}, StateData) ->
true -> {stop, normal, StateData};
false -> {next_state, normal_state, StateData}
end;
+normal_state({route, Nick, #presence{from = From, lang = Lang} = Packet}, StateData)
+ when From#jid.luser /= Nick ->
+ ErrText = <<"It is not allowed to join the room with nickname different than username">>,
+ Err = xmpp:err_forbidden(ErrText, Lang),
+ ejabberd_router:route_error(Packet, Err),
+ case StateData#state.just_created of
+ true -> {stop, normal, StateData};
+ false -> {next_state, normal_state, StateData}
+ end;
normal_state({route, Nick, #presence{from = From} = Packet}, StateData) ->
Activity = get_user_activity(From, StateData),
Now = p1_time_compat:system_time(micro_seconds),

You don't want occupants of a room to change their nickname. The rooms have an option to disallow "visitors" to change their nickname.
But maybe you also want to disallow "participants": there isn't any option for that, but it is possible to modify ejabberd source code, and recompile it, see the third patch that I provided in Remove some options from room config MUC

Related

How to give a mysql record a timeout to expire after 30 minutes?

I was not able to find something relevant anywhere.
I would like to put a timeout on "password" that I am saving on mysql with python.
cur.execute("INSERT INTO generatedcode(password, codetimeout) VALUES (%s,
%s)", [passwordd, timestamp])
As I'm not sufficiently acquainted with python and hence I'll leave the specifics of the code to you; I will only present the idea of the solution and the relevant SQL commands (syntax will need to be verified as I don't have an environment to test it).
Let say that you want to set a timeout of 1 hour from the moment you save the password and your table has (at least) the following two fields: Password and Expiration (I assume that Password would be of binary type to allow encryption and Expiration would be of DATETIME type).
Then, you would implement the following SQL command:
INSERT INTO <your table> (Password , Expiration )
VALUES (%s , DATEADD(NOW(),3600))
[spaces added just for clarity purposes]
and send that string towards the DB where %s would be replaced by the value of the password.
What DATEADD(NOW(),3600) does is:
Gets the current date and time,
Adds one hour to it.
Once you have that inserted into your table, you would later on retrieve the password using the following command:
SELECT Password
FROM <your table>
WHERE User = <could be Username or any other key that you are using now>
AND Expiration > NOW()
meaning, get the password (if any) that its expiration datetime is still in the future.
Hope this is what you were looking for.
Cheers!!
EDIT:
I'm adding hereinafter your code after fixes:
#app.route('/signattendance', methods=['GET'])
def signattendance():
stamp = "signed"
error = None
# now = datetime.datetime.today()
# tdelta = datetime.timedelta(seconds=10000)
now = datetime.datetime.now()
if request.method == 'GET':
cur1 = mysql.connection.cursor()
result = cur1.execute("SELECT password FROM generatedcode WHERE codetimeout > NOW()")
if result is False:
cur = mysql.connection.cursor()
cur.execute("INSERT INTO attendance(studentattendance) VALUES(%s,DATEADD(NOW(),3600)", [stamp])
mysql.connection.commit()
cur.close()
# cur1.close()
flash('Succsefully signed', 'Acepted')
else:
flash('You couldnt sign attendance', 'Denied')
else:
return redirect(url_for('dashboard'))
return render_template('signattendance.html', error=error)
Note that I leave for the DB to check the current time.
if request.method == 'GET' or 'POST':
cur1 = mysql.connection.cursor()
result = cur1.execute("SELECT password FROM generatedcode "
"WHERE DATE_SUB(CURRENT_TIME (),INTERVAL 10 MINUTE) <= codetimeout;")

odoo 9 migrate binary field db to filestore

Odoo 9 custom module binary field attachment=True parameter added later after that new record will be stored in filesystem storage.
Binary Fields some old records attachment = True not used, so old record entry not created in ir.attachment table and filesystem not saved.
I would like to know how to migrate old records binary field value store in filesystem storage?. How to create/insert records in ir_attachment row based on old records binary field value? Is any script available?
You have to include the postgre bin path in pg_path in your configuration file. This will restore the file store that contains the binary fields
pg_path = D:\fx\upsynth_Postgres\bin
I'm sure that you no longer need a solution to this as you asked 18 months ago, but I have just had the same issue (many gigabytes of binary data in the database) and this question came up on Google so I thought I would share my solution.
When you set attachment=True the binary column will remain in the database, but the system will look in the filestore instead for the data. This left me unable to access the data from the Odoo API so I needed to retrieve the binary data from the database directly, then re-write the binary data to the record using Odoo and then finally drop the column and vacuum the table.
Here is my script, which is inspired by this solution for migrating attachments, but this solution will work for any field in any model and reads the binary data from the database rather than from the Odoo API.
import xmlrpclib
import psycopg2
username = 'your_odoo_username'
pwd = 'your_odoo_password'
url = 'http://ip-address:8069'
dbname = 'database-name'
model = 'model.name'
field = 'field_name'
dbuser = 'postgres_user'
dbpwd = 'postgres_password'
dbhost = 'postgres_host'
conn = psycopg2.connect(database=dbname, user=dbuser, password=dbpwd, host=dbhost, port='5432')
cr = conn.cursor()
# Get the uid
sock_common = xmlrpclib.ServerProxy ('%s/xmlrpc/common' % url)
uid = sock_common.login(dbname, username, pwd)
sock = xmlrpclib.ServerProxy('%s/xmlrpc/object' % url)
def migrate_attachment(res_id):
# 1. get data
cr.execute("SELECT %s from %s where id=%s" % (field, model.replace('.', '_'), res_id))
data = cr.fetchall()[0][0]
# Re-Write attachment
if data:
data = str(data)
sock.execute(dbname, uid, pwd, model, 'write', [res_id], {field: str(data)})
return True
else:
return False
# SELECT attachments:
records = sock.execute(dbname, uid, pwd, model, 'search', [])
cnt = len(records)
print cnt
i = 0
for res_id in records:
att = sock.execute(dbname, uid, pwd, model, 'read', res_id, [field])
status = migrate_attachment(res_id)
print 'Migrated ID %s (attachment %s of %s) [Contained data: %s]' % (res_id, i, cnt, status)
i += 1
cr.close()
print "done ..."
Afterwards, drop the column and vacuum the table in psql.

MySql Database connection with python

I've got an issue trying to connect to a database with python. It compiles without error but it doesn't seem to do anything. I'm not sure if I'm instantiating the class incorrectly or what the issue may be. Could someone point me in the right direction?
import _mysql
import MySQLdb
class Operations:
def open():
db=_mysql.connect("127.0.0.1","root","admin","test")
c=db.cursor()
#deletes the cursor
def close(self):
c.close()
#verifies the credentials and advances
def login(self):
print "Welcome to the online bookstore login!"
x = raw_input('Please enter your user id. ')
y = raw_input('Please enter your password. ')
c.execute("""SELECT userid,password FROM members WHERE userid = %s""", (x,))
z = c.password
if y == z:
member_menu()
else:
close()
def new_user(self):
print "Welcome to the Online book store new user registration page!"
print "To begin, please enter your first name: "
fName = raw_input('Please enter your first name: ')
lName = raw_input('Please enter your last name: ')
address = raw_input('Please enter your street address: ')
city = raw_input('Please enter your city: ')
state = raw_input('Please enter your state: ')
zip_code = raw_input('Please enter your zip code: ')
phone = raw_input('Please enter your phone number: ')
email = raw_input('Please enter your email: ')
user_ID = raw_input('Please enter your user id: ')
password = raw_input('Please enter your password: ')
c.executemany("""INSERT INTO members(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,) VALUES (fName, lName, address, city, state, zip_code, phone, email, user_id, password,)""")
print "Your account has been created. returning to the welcome menu. "
welcome()
def welcome(self):
choice = NONE;
print "**********************************************************************\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "***\t\tWelcome to the Online Book Store\t\t ***\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "**********************************************************************\n"
print "1. Member Login\n"
print "2. New Member Registration\n"
print "3. Quit\n"
choice = raw_input('Type in your option: ')
if choice == 1:
login()
elif x == 2:
new_user()
else:
close()
def member_menu(self):
x = NONE
print "**********************************************************************\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "***\t\t Welcome to the Online Book Store \t\t ***\n"
print "***\t\t\t Member Menu \t\t\t ***\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "**********************************************************************\n"
print "1. Search by Author/Title/Subject\n"
print "2. View/Edit Shopping Cart\n"
print "3. Check Order Status\n"
print "4. One Click Check Out\n"
print "5. Logout\n"
print "Type in your option: "
x = raw_input('Please enter your choice. ')
if x == 1:
close_conn(),
elif x == 2:
close_conn(),
elif x == 3:
close_conn(),
elif x == 4:
close_conn(),
else:
close_conn()
def main():
start = Operations()
print "Opening conenction to database"
start.welcome
if __name__ == '__main__':
main()
Well, there are so many problems with your code, that I'll probably miss some of them anyway.
Nothing happens, because your main() function and condition are both parts of the class definition, so all the interpreter sees are actually two imports and a class definition.
Let's say we unindented the main() definition and the condition. All that would happen then is creating an instance of Operations (with no special effects, as you have no custom constructor defined) and printing "Opening connection to database" to the screen, because all the last line in main() does is getting a reference to the welcome() method and ignoring it. You need to call it: start.welcome()
When you do call it, much more problems will appear. NameErrors will probably come first, as you are using identifiers that do not exist in given scopes. It seems you're new to Python's object model and probably coming from a language with a different approach, like C++. In Python all non-static and non-class instance methods take a reference to the object they're operating on as the first parameter, traditionally called 'self'. If you want to access any of the fields of the object, you need to do this through 'self', they are not visible to the interpreter otherwise. E.g.: you open a connection and keep the cursor as c, which you later reuse in other methods:
def open():
# ...
c=db.cursor()
# ...
def login(self):
# ...
c.execute("...")
That's incorrect for two reasons:
your open() method does not take self as a parameter
you're creating c as a local variable in scope of the open() method and then trying to access it in login(), which essentialy results in a "reference before assignment" error.
In order to be correct, it should be written like this:
def open(self):
# ...
self.c = db.cursor()
# ...
def login(self):
# ...
self.c.execute("...")
You're making the same mistake in many places. You need to call self.login(), self.new_user(), self.close(), etc.
You're using Python 2, at least according to the question's tags and there is one thing you need to remember when declaring classes in Python 2. There exist so called old- and new-style classes and what you want to do is use the new-style ones. Therefore your class must inherit from object:
class Operations(object):
# ...
They've finally decided to drop the old-style classes support in Python 3 and there's no need to explicitly inherit from object anymore, but while in Python 2, you need to cope with it.
While there are still some errors or potential errors (what is close_connection()?), I think it's enough for a good start ;). Good luck.

python-mysql fetchone() type mismatch?

I have this piece of code that should return the value of the password from the db and match it with the password entered. I appended the characters on this line to match the formatting of the result that it printed.
appended_y= "(u'" + y + "'y,)"
it even though the two print out the same value the if statement rejects it and always falls to else, Can anyone point me down the right path?
print "Welcome to the online bookstore login!"
x = raw_input('Please enter your user id. ')
y = raw_input('Please enter your password. ')
appended_y= "(u'" + y + "'y,)"
z = "SELECT password FROM members WHERE userid = %s"
self.cursor.execute(z,(x,))
pw=(self.cursor.fetchone())
if appended_y == pw:
self.member_menu()
else:
print "Incorrect name or password. Aborting connection"
Look into the type of pw. It may be a string inside a list or tuple.

Persist an entity with a user reference in Yesod?

I'm changing my existing Yesod application to run on a SQL backend instead of mongo. The generated table structure is more strict then the mongo backend. Foreign key references should be created correctly on insert.
postFeedingsR :: Handler RepJson
postFeedingsR = do
muser <- maybeAuth
parsedFeeding <- parseJsonBody_ --get content as JSON
let userId = getUserId muser
let feedingWithUser = Feeding (feedingDate parsedFeeding) (feedingSide parsedFeeding) (feedingTime parsedFeeding) (feedingExcrements parsedFeeding) (feedingRemarks parsedFeeding) userId --should be linked to user..
fid <- runDB $ insert feedingWithUser --store in database
--runDB $ update fid [ FeedingUserId =. userId ] --Old mongo style of linking the feeding to the user
sendResponseCreated $ FeedingR fid --return the id
I try to update the Entity I get from parseJsonBody with the user UID from the maybeAuth. However this gives me the following error:
No instance for (aeson-0.6.0.2:Data.Aeson.Types.Class.FromJSON
(FeedingGeneric backend0))
arising from a use of `parseJsonBody_'
Possible fix:
add an instance declaration for
(aeson-0.6.0.2:Data.Aeson.Types.Class.FromJSON
(FeedingGeneric backend0))
In a stmt of a 'do' block: parsedFeeding <- parseJsonBody_
In the expression:
do { muser <- maybeAuth;
parsedFeeding <- parseJsonBody_;
let userId = getUserId muser;
let feedingWithUser
= Feeding
(feedingDate parsedFeeding)
(feedingSide parsedFeeding)
(feedingTime parsedFeeding)
(feedingExcrements parsedFeeding)
(feedingRemarks parsedFeeding)
userId;
.... }
In an equation for `postFeedingsR':
postFeedingsR
= do { muser <- maybeAuth;
parsedFeeding <- parseJsonBody_;
let userId = ...;
.... }
I'm not sure why this happens. Could anyone put me in the right direction to solve this?
Solved by changing the auth line to:
Entity uid u <- requireAuth
and by adding the function:
addUserToFeeding :: UserId -> Feeding -> Feeding
addUserToFeeding uid Feeding {feedingDate=date, feedingSide=side, feedingTime=time, feedingExcrements=ex, feedingRemarks=remarks} = Feeding date side time ex remarks uid
to create a new Feeding with associated user. This Feeding can then be stored in the normal way in Yesod:
let feedingWithUser = addUserToFeeding uid parsedFeeding
fid <- runDB $ insert feedingWithUser --store in database