Skip to content

Commit

Permalink
Rubocopd. params[:format] is now set in post.
Browse files Browse the repository at this point in the history
  • Loading branch information
elifoster committed Oct 5, 2015
1 parent 27b1cc2 commit f01fe4d
Show file tree
Hide file tree
Showing 8 changed files with 455 additions and 386 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Changelog
## Version 0
### Version 0.4.1
* params[:format] is now automatically set to 'json', so it no longer needs to be defined in each method.
* Fixed a lot of styling issues thanks to Rubocop.
* check_login and check_create now use case/when statements instead of elsifs.
* check_create no longer returns anything.
* Update minimum Ruby version to 2.1, for refinements.
Expand Down
182 changes: 95 additions & 87 deletions lib/mediawiki/auth.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,125 +2,128 @@

module MediaWiki
module Auth

# Checks the login result for errors. Returns true if it is successful, else false with an error raised.
# Checks the login result for errors. Returns true if it is successful,
# else false with an error raised.
# @param result [String] The parsed version of the result.
# @param secondtry [Boolean] Whether this login is the first or second try. False for first, true for second.
# @param secondtry [Boolean] Whether this login is the first or second try.
# False for first, true for second.
# @return [Boolean] true if successful, else false.
def check_login(result, secondtry)
case result
when "Success"
when 'Success'
@logged_in = true
return true
when "NeedToken"
when 'NeedToken'
if secondtry == true
raise MediaWiki::Butt::NeedTokenMoreThanOnceError
fail MediaWiki::Butt::NeedTokenMoreThanOnceError
return false
end
when "NoName"
raise MediaWiki::Butt::NoNameError
when 'NoName'
fail MediaWiki::Butt::NoNameError
return false
when "Illegal"
raise MediaWiki::Butt::IllegalUsernameError
when 'Illegal'
fail MediaWiki::Butt::IllegalUsernameError
return false
when "NotExists"
raise MediaWiki::Butt::UsernameNotExistsError
when 'NotExists'
fail MediaWiki::Butt::UsernameNotExistsError
return false
when "EmptyPass"
raise MediaWiki::Butt::EmptyPassError
when 'EmptyPass'
fail MediaWiki::Butt::EmptyPassError
return false
when "WrongPass"
raise MediaWiki::Butt::WrongPassError
when 'WrongPass'
fail MediaWiki::Butt::WrongPassError
return false
when "WrongPluginPass"
raise MediaWiki::Butt::WrongPluginPassError
when 'WrongPluginPass'
fail MediaWiki::Butt::WrongPluginPassError
return false
when "CreateBlocked"
raise MediaWiki::Butt::CreateBlockedError
when 'CreateBlocked'
fail MediaWiki::Butt::CreateBlockedError
return false
when "Throttled"
raise MediaWiki::Butt::ThrottledError
when 'Throttled'
fail MediaWiki::Butt::ThrottledError
return false
when "Blocked"
raise MediaWiki::Butt::BlockedError
when 'Blocked'
fail MediaWiki::Butt::BlockedError
return false
end
end

# Checks the account creation result's error and raises the corresponding error.
# @param error [String] The parsed error "code" string
# Checks the account creation result's error and raises the corresponding
# exception.
# @param error [String] The parsed error code string
def check_create(error)
case error
when "noname"
raise MediaWiki::Butt::NoNameError
when "userexists"
raise MediaWiki::Butt::UserExistsError
when "password-name-match"
raise MediaWiki::Butt::UserPassMatchError
when "password-login-forbidden"
raise MediaWiki::Butt::PasswordLoginForbiddenError
when "noemailtitle"
raise MediaWiki::Butt::NoEmailTitleError
when "invalidemailaddress"
raise MediaWiki::Butt::InvalidEmailAddressError
when "passwordtooshort"
raise MediaWiki::Butt::PasswordTooShortError
when "noemail"
raise MediaWiki::Butt::NoEmailError
when "acct_creation_throttle_hit"
raise MediaWiki::Butt::ThrottledError
when "aborted"
raise MediaWiki::Butt::AbortedError
when "blocked"
raise MediaWiki::Butt::BlockedError
when "permdenied-createaccount"
raise MediaWiki::Butt::PermDeniedError
when "createaccount-hook-aborted"
raise MediaWiki::Butt::HookAbortedError
when 'noname'
fail MediaWiki::Butt::NoNameError
when 'userexists'
fail MediaWiki::Butt::UserExistsError
when 'password-name-match'
fail MediaWiki::Butt::UserPassMatchError
when 'password-login-forbidden'
fail MediaWiki::Butt::PasswordLoginForbiddenError
when 'noemailtitle'
fail MediaWiki::Butt::NoEmailTitleError
when 'invalidemailaddress'
fail MediaWiki::Butt::InvalidEmailAddressError
when 'passwordtooshort'
fail MediaWiki::Butt::PasswordTooShortError
when 'noemail'
fail MediaWiki::Butt::NoEmailError
when 'acct_creation_throttle_hit'
fail MediaWiki::Butt::ThrottledError
when 'aborted'
fail MediaWiki::Butt::AbortedError
when 'blocked'
fail MediaWiki::Butt::BlockedError
when 'permdenied-createaccount'
fail MediaWiki::Butt::PermDeniedError
when 'createaccount-hook-aborted'
fail MediaWiki::Butt::HookAbortedError
end
end

# Logs the user into the wiki. This is generally required for editing and getting restricted data. Will return the result of #check_login
# Logs the user into the wiki. This is generally required for editing and
# getting restricted data. Will return the result of #check_login
# @param username [String] The username
# @param password [String] The password
# @return [Boolean] True if the login was successful, false if not.
def login(username, password)
params = {
action: 'login',
lgname: username,
lgpassword: password,
format: 'json'
lgpassword: password
}

result = post(params)
if check_login(result["login"]["result"], false)
if check_login(result['login']['result'], false)
@logged_in = true
@tokens.clear
true
elsif result["login"]["result"] == "NeedToken" && result["login"]["token"] != nil
token = result["login"]["token"]
elsif result['login']['result'] == 'NeedToken' &&
!result['login']['token'].nil?
token = result['login']['token']
token_params = {
action: 'login',
lgname: username,
lgpassword: password,
format: 'json',
lgtoken: token
}

#Consider refactor the @cookie initialization.
@cookie = "#{result["login"]["cookieprefix"]}Session=#{result["login"]["sessionid"]}"
result = post(token_params, true, { 'Set-Cookie' => @cookie })
check_login(result["login"]["result"], true)
# Consider refactor the @cookie initialization.
@cookie = "#{result['login']['cookieprefix']}" \
"Session=#{result['login']['sessionid']}"
result = post(token_params, true, 'Set-Cookie' => @cookie)
check_login(result['login']['result'], true)
end
end

# Logs the current user out.
# @return [Boolean] True if it was able to log anyone out, false if not (basically, if someone was logged in, it returns true).
# @return [Boolean] True if it was able to log anyone out, false if not
# (basically, if someone was logged in, it returns true).
def logout
if @logged_in
params = {
action: 'logout',
format: 'json'
action: 'logout'
}

post(params)
Expand All @@ -135,8 +138,11 @@ def logout
# Creates an account using the standard procedure.
# @param username [String] The desired username.
# @param password [String] The desired password.
# @param language [String] The language code to be set as default for the account. Defaults to 'en', or English. Use the language code, not the name.
# @param reason [String] The reason for creating the account, as shown in the account creation log. Optional.
# @param language [String] The language code to be set as default for the
# account. Defaults to 'en', or English. Use the language code, not
# the name.
# @param reason [String] The reason for creating the account, as shown in
# the account creation log. Optional.
# @return [Boolean] True if successful, false if not.
def create_account(username, password, language = 'en', *reason)
params = {
Expand All @@ -148,28 +154,28 @@ def create_account(username, password, language = 'en', *reason)
}

result = post(params)
if result["error"] != nil
check_create(result["error"]["code"])
unless result['error'].nil?
check_create(result['error']['code'])
return false
end

if result["createaccount"]["result"] == "Success"
if result['createaccount']['result'] == 'Success'
@tokens.clear
return true
elsif result["createaccount"]["result"] == "NeedToken"
elsif result['createaccount']['result'] == 'NeedToken'
params = {
name: username,
password: password,
reason: reason,
language: language,
token: result["createaccount"]["token"]
token: result['createaccount']['token']
}

result = post(params, true, true)
if result["error"] != nil
check_create(result["error"]["code"])
if !result['error'].nil?
check_create(result['error']['code'])
return false
elsif result["createaccount"]["result"] == "Success"
elsif result['createaccount']['result'] == 'Success'
return true
else
return false
Expand All @@ -180,8 +186,11 @@ def create_account(username, password, language = 'en', *reason)
# Creates an account using the random password sent by email procedure.
# @param username [String] The desired username
# @param email [String] The desired email address
# @param language [String] The language code to be set as default for the account. Defaults to 'en', or English. Use the language code, not the name.
# @param reason [String] The reason for creating the account, as shown in the account creation log. Optional.
# @param language [String] The language code to be set as default for the
# account. Defaults to 'en', or English. Use the language code, not
# the name.
# @param reason [String] The reason for creating the account, as shown in
# the account creation log. Optional.
# @return [Boolean] True if successful, false if not.
def create_account_email(username, email, language = 'en', *reason)
params = {
Expand All @@ -194,30 +203,29 @@ def create_account_email(username, email, language = 'en', *reason)
}

result = post(params)
result = post(params)
if result["error"] != nil
check_create(result["error"]["code"])
unless result['error'].nil?
check_create(result['error']['code'])
return false
end

if result["createaccount"]["result"] == "Success"
if result['createaccount']['result'] == 'Success'
@tokens.clear
return true
elsif result["createaccount"]["result"] == "NeedToken"
elsif result['createaccount']['result'] == 'NeedToken'
params = {
name: username,
email: email,
mailpassword: 'value',
reason: reason,
language: language,
token: result["createaccount"]["token"]
token: result['createaccount']['token']
}

result = post(params, true, true)
if result["error"] != nil
check_create(result["error"]["code"])
if !result['error'].nil?
check_create(result['error']['code'])
return false
elsif result["createaccount"]["result"] == "Success"
elsif result['createaccount']['result'] == 'Success'
return true
else
return false
Expand Down
55 changes: 37 additions & 18 deletions lib/mediawiki/butt.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ class Butt
include MediaWiki::Constants::Namespaces
include MediaWiki::Edit

# Creates a new instance of MediaWiki::Butt. To work with any MediaWiki::Butt methods, you must first create an instance of it.
#
# @param url [String] The FULL wiki URL. api.php can be omitted, but it will make harsh assumptions about your wiki configuration.
# Creates a new instance of MediaWiki::Butt. To work with any
# MediaWiki::Butt methods, you must first create an instance of it.
# @param url [String] The FULL wiki URL. api.php can be omitted, but it
# will make harsh assumptions about your wiki configuration.
# @param use_ssl [Boolean] Whether or not to use SSL. Will default to true.
# @return [MediaWiki::Butt] new instance of MediaWiki::Butt
def initialize(url, use_ssl = true)
Expand All @@ -29,18 +30,32 @@ def initialize(url, use_ssl = true)
@tokens = {}
end

# Performs a generic HTTP POST action and provides the response. This method generally should not be used by the user, unless there is not a method provided by the Butt developers for a particular action.
#
# @param params [Hash] A basic hash containing MediaWiki API parameters. Please see the MediaWiki API for more information.
# @param autoparse [Boolean] Whether or not to provide a parsed version of the response's JSON. Will default to true.
# Performs a generic HTTP POST action and provides the response. This
# method generally should not be used by the user, unless there is not a
# method provided by the Butt developers for a particular action.
# @param params [Hash] A basic hash containing MediaWiki API parameters.
# Please see the MediaWiki API for more information.
# @param autoparse [Boolean] Whether or not to provide a parsed version
# of the response's JSON. Will default to true.
# @param header [Hash] The header hash. Optional.
# @return [JSON/HTTPMessage] Parsed JSON if autoparse is true, or raw response if not.
# @return [JSON/HTTPMessage] Parsed JSON if autoparse is true, or raw
# response if not.
def post(params, autoparse = true, header = nil)
# Note that defining the header argument as a splat argument (*header) causes errors in HTTPClient.
# We must use header.nil? rather than a splat argument and defined? header due to this error.
# For those interested, the error is: undefined method `downcase' for {"Set-Cookie"=>"cookie"}:Hash (NoMethodError)
# This is obvisouly an error in HTTPClient, but we must work around it until there is a fix in the gem.
res = header.nil? ? @client.post(@uri, params) : @client.post(@uri, params, header)
# Note that defining the header argument as a splat argument (*header)
# causes errors in HTTPClient. We must use header.nil? rather than a
# splat argument and defined? header due to this error. For those
# interested, the error is:
# undefined method `downcase' for {"Set-Cookie"=>"cookie"}:Hash
# This is obvisouly an error in HTTPClient, but we must work around it
# until there is a fix in the gem.

params[:format] = 'json'

if header.nil?
res = @client.post(@uri, params)
else
res = @client.post(@uri, params, header)
end

if autoparse
return JSON.parse(res.body)
Expand All @@ -49,14 +64,18 @@ def post(params, autoparse = true, header = nil)
end
end

# Returns true if the currently logged in user is in the "bot" group. This can be helpful to some developers, but it is mostly for use internally in MediaWiki::Butt.
# @param username [String] The username to check. Optional. Defaults to the currently logged in user if nil.
# @return [Boolean] true if logged in as a bot, false if not logged in or logged in as a non-bot
def is_user_bot?(*username)
# Returns true if the currently logged in user is in the "bot" group.
# This can be helpful to some developers, but it is mostly for use
# internally in MediaWiki::Butt.
# @param username [String] The username to check. Optional. Defaults to
# the currently logged in user if nil.
# @return [Boolean] true if logged in as a bot, false if not logged in or
# logged in as a non-bot
def user_bot?(*username)
groups = defined? username ? get_usergroups(username) : get_usergroups

if groups != false
return groups.include?("bot")
return groups.include?('bot')
else
return false
end
Expand Down
Loading

0 comments on commit f01fe4d

Please sign in to comment.